Tuesday, November 5, 2013

Delegate in c# Part 2 (Asynchronous Communication Using Delegate)


Delegate in c# Part 2 (Asynchronous Communication Using Delegate)


                This article will give you brief description about Asynchronous communication using delegate, for more information about delegate, visit my previous article about delegate with simple example,

                Based on type of calling delegate, its two types
                                1.  Synchronous Delegate
                                2. Asynchronous Delegate

1. Synchronous Delegate:

                In this type of delegate the process flow is maintained in same thread, once the process completes, its move to next line, for example in Database related operation, it may take some 1 or 2minutes means, the process need to wait for operation to complete, then it moves to next line of execution, it’s an old, time taken and traditional way of programming.

2. Asynchronous Delegate:

                In this type of delegate the process flow is maintained in separate thread, in the above process flow diagram, step 2 is maintained in separate thread. In this type of delegate, the statement after the asynchronous call will continue execution, once the process completes, it invoke the method associated with it.

Example,

                For asynchronous Delegate declaration and initialization is same as normal delegate, invoking the delegate is quite different.

Delegate Declaration

public delegate DataSet DelegateGetBulkData(ulong rows);//delegate declaration

Delegate Initialization:

DelegateGetBulkData dataDelegate = new DelegateGetBulkData(db.GetBulkDatas);//delegate initialization

Delegate invocation

IAsyncResult asycResult = dataDelegate.BeginInvoke(rows, new AsyncCallback(GetBulkDataCompleted), null);//delegate invocation

                In the above invocation, GetBulkDataCompleted is a method which needs to be called after the process completed. It should always has IAsyncResult as input parameter to get asynchronous result.

       Method Example:

void GetBulkDataCompleted(IAsyncResult result)
            {
            if (result is AsyncResult)
            {
                DelegateGetBulkData actualResult = (result as AsyncResult).AsyncDelegate as DelegateGetBulkData;
                DataSet dsResult = actualResult.EndInvoke(result);
                result.AsyncWaitHandle.Close();
                CompleteCallMethod(dsResult, syncContext);// call UI method to assign data
            }

        } 


SynchronizationContext

       In asynchronous communication, a window control can’t be accessed by multiple threads, so we need of synchronization context to update data in control, for more information about Synchronization context refer MS site.



Project description:

1. SampleDataBase.csproj: DLL for database operation.
2.  AsyncProg: class file which contain actual asynchronous implementation.



No comments:

Post a Comment