Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement Asynchronous Operation in C #

2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article is about how C # implements asynchronous operations. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

The .NET Framework provides two design modes for asynchronous operations: asynchronous operations using IAsyncResult objects and asynchronous operations using events. Let's learn the former first.

Overview

The IAsyncResult asynchronous design pattern implements asynchronous calls to the original synchronous methods through two methods named BeginOperationName and EndOperationName. For example, the FileStream class provides BeginRead and EndRead methods to asynchronously read bytes from a file, which are asynchronous versions of the Read method.

The Begin method contains any parameters in the synchronous method signature, in addition to two other parameters: an AsyncCallback delegate and a user-defined state object. Delegates are used to call callback methods, and state objects are used to pass state information to callback methods. This method returns an object that implements the IAsyncResult interface

The End method is used to end the C# asynchronous operation and return the result, so it contains the ref and out parameters in the synchronous method signature, and the return value type is the same as the synchronous method. The method also includes an IAsyncResult parameter, which is used to obtain information about whether the asynchronous operation is completed. Of course, when using it, you must pass in the object instance returned by the corresponding Begin method.

If you want to block the application after starting the C# asynchronous operation, you can call the End method directly, which prevents the application from continuing execution until the asynchronous operation is complete. You can also use the AsyncWaitHandle property of IAsyncResult and call methods such as WaitOne to block the thread. There is not much difference between the two methods, except that the former must wait all the time while the latter can set a wait timeout

If you do not block the application, you can determine whether the operation is complete by polling the IsCompleted state of the IAsyncResult, or you can use the AsyncCallback delegate to end the C# asynchronous operation. The AsyncCallback delegate contains an IAsyncResult signature, and the End method is called inside the callback method to get the execution result of the operation.

Try

Let's familiarize ourselves with today's protagonist, the IAsyncResult interface.

Public interface IAsyncResult {object AsyncState {get;} WaitHandle AsyncWaitHandle {get;} bool CompletedSynchronously {get;} bool IsCompleted {get;}}

I use an AsyncDemo class as the provider of asynchronous methods, which is called by subsequent programs. The inside is simple: the constructor takes a string as name, the Run method outputs "My name is" + name, and the asynchronous method is implemented directly with delegated BeginInvoke and EndInvoke methods.

Public class AsyncDemo {/ / Use in asynchronous methods private delegate string runDelegate (); private string masked name; private runDelegate masked Delete; public AsyncDemo (string name) {m_Name = name; m_Delegate = new runDelegate (Run);} / * / Synchronous method / public string Run () {return "My name is" + m_Name } / * * / Asynchronous begin method / public IAsyncResult BeginRun (AsyncCallback callBack, Object stateObject) {try {return m_Delegate.BeginInvoke (callBack, stateObject);} catch (Exception e) {/ / Hide inside method invoking stack throw e }} / * / Asynchronous end method / public string EndRun (IAsyncResult ar) {if (ar = = null) throw new NullReferenceException ("Arggument ar can't be null"); try {return m_Delegate.EndInvoke (ar);} catch (Exception e) {/ / Hide inside method invoking stack throw e;}

First, the End method is called directly after Begin, and of course other operations can be done in the middle.

Class AsyncTest {static void Main (string [] args) {AsyncDemo demo = new AsyncDemo ("jiangnii"); / / Execute begin method IAsyncResult ar = demo.BeginRun (null, null); / / You can do other things here / / Use end method to block thread until the operation is complete string demodemoName = demo.EndRun (ar); Console.WriteLine (demoName);}}

You can also use the AsyncWaitHandle property of IAsyncResult, which I set here to time out for 1 second.

Class AsyncTest {static void Main (string [] args) {AsyncDemo demo = new AsyncDemo ("jiangnii"); / / Execute begin method IAsyncResult ar = demo.BeginRun (null, null); / / You can do other things here / / Use AsyncWaitHandle.WaitOne method to block thread for 1 second at most ar.AsyncWaitHandle.WaitOne (1000, false); if (ar.IsCompleted) {/ / Still need use end method to get result, / / but this time it will return immediately string demodemoName = demo.EndRun (ar); Console.WriteLine (demoName) } else {Console.WriteLine ("Sorry, can't get demoName, the time is over");}

Uninterrupted round robin, outputting one "."

Class AsyncTest {static void Main (string [] args) {AsyncDemo demo = new AsyncDemo ("jiangnii"); / / Execute begin method IAsyncResult ar = demo.BeginRun (null, null); Console.Write ("Waiting.."); while (! ar.IsCompleted) {Console.Write ("."); / / You can do other things here} Console.WriteLine (); / / Still need use end method to get result, / / but this time it will return immediately string demodemoName = demo.EndRun (ar) Console.WriteLine (demoName);}}

* the callback method is used and a state object is added, which is passed to the callback method as the AsyncState attribute of the IAsyncResult parameter. The main thread cannot exit before the callback method is executed. I simply let it hibernate for 1 second. Another difference is that the AsyncDemo object is defined as a static field of the class so that the callback method can use the

Class AsyncTest {static AsyncDemo demo = new AsyncDemo ("jiangnii"); static void Main (string [] args) {/ / State object bool state = false; / / Execute begin method IAsyncResult ar = demo.BeginRun (new AsyncCallback (outPut), state); / / You can do other thins here / / Wait until callback finished System.Threading.Thread.Sleep (1000);} / / Callback method static void outPut (IAsyncResult ar) {bool state = (bool) ar.AsyncState; string demodemoName = demo.EndRun (ar) If (state) {Console.WriteLine (demoName);} else {Console.WriteLine (demoName + ", isn't it?");}

Summary of C # Asynchronous Operation

For an object that has already implemented the BeginOperationName and EndOperationName methods, we can call it directly in the above way, but for an object with only synchronous methods, we do not need to add corresponding asynchronous methods to make asynchronous calls, instead, we only need to define a delegate and use its BeginInvoke and EndInvoke methods.

Thank you for reading! This is the end of this article on "how to implement asynchronous operation in C#". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report