Compartir a través de


.Net : Asynchronous Programming Techniques – Part II

Hi There,

I am Syam Pinnaka, Dev in IAM services team at Microsoft.

As promised in my last post, lets examine event based Asynchronous Programming Technique.

The key difference between IAsyncResult and Event based pattern is the way they notify the client when  asynchronous call is completed. While using the IAsyncResult pattern, client will either wait on the call they made with “BeginInvokeXXX” or wait for the callback method to be called which it has supplied to the “BeginInvokeXXX” method. In event based pattern, client can subscribe to a completion event and then the client will be notified using this subscribed event when the Asynchronous call is completed. The event based Asynchronous class signature will look something similar to below.

         /// <summary>
        /// Event for when writing to log file is completed.
        /// </summary>
        public event EventHandler CompletedWriting;

Client can subscribe to this event as shown below.

             LogFileWriter logFileWriter = new LogFileWriter();
            logFileWriter.CompletedWriting += OnCompletedWriting;
 And call a method which operates Asynchronously.
             logFileWriter.WriteLineAsync(charsToLog);

The WriteLineAsync method which will look like below.

         /// <summary>
        /// WriteLineAsync to start write to file asychronously.
        /// </summary>
        /// <param name="line">Text to write</param>
        public void WriteLineAsync(string line)
        {
            IAsyncResult result = writelineToLogfile.BeginInvoke(line, callback, state);
            result.AsyncWaitHandle.WaitOne();
            CompletedWriting(this, null);
        }

Note in the above code that writelineToLogfile is a delegate to the actual method which does the writing work. When this call is completed, WaitOne will receive the signal to resume execution which will then call “CompletedWriting” to notify the client about Asynchronous call completion. This can also be done in “callback” argument method and thus “WaitOne” can be avoided.

Also note the second argument in CompletedWriting event which is null now. This argument can be used to pass back some useful information to the client when the Asynchronous call is completed. The CompletedWriting event declaration will need a change like below.

         public event EventHandler<CompletedWritingEventArgs> CompletedWriting;

CompletedWritingEventArgs is a class derived from EventArgs as show below.

   internal class CompletedWritingEventArgs : EventArgs
  {
      public double BytesWritten;
  }

That’s all for now and all the best with your asynchronous programming designs and code!

 

Technorati Tags: .Net,Asynchronous programming