Skip to main content

Asynchronous Programming Model(APM) with .Net



Namespace: System.Threading

Asynchronous programming is simply allowing some portion of code to be executed on separate threads. Many .Net Framework classes support APM with methods like BeginXXX and EndXXX.

FileStream FS = new Filestream(Filename, FileMode.Open, FileAccess.Read, FileShare.Read, 1024, FileOptions.Asynchronous);

IAsyncResult vResult = FS.BeginRead(buffer, 0 , Buffer.length, null, null);

//Do your work

int NoOfBytes = FS.EndRead(vResult);
FS.Close();

This type of APM is 1. Rendezvous Wait-Until-Done model.

2. Rendezvous Polling Model:
Keeping doing some other work along with checking whether the APM work is completed or not.

IAsyncResult vResult = FS.BeginRead(buffer, 0 , Buffer.length, null, null);

While ( ! vResult.IsCompleted )
{
//Do your work
}

int NoOfBytes = FS.EndRead(vResult);
FS.Close();

3. Callback Model:
                Register a callback to notify you about the APM work ended.

IAsyncResult vResult = FS.BeginRead(    buffer, 0 , Buffer.length,
new AsyncCallback ( ReadCompleted),
 FS);

static void CompletedRead(IASyncResult V)
{
                FileStream FS = (FileStream) v.SyncState;
                Int NoOfBytes = FS.EndRead();
                FS.Close();
}

Exception Handling:

All exceptions are hold downed and thrown when End method of APM is called. So wrap EndXXX calls in try/catch block.

Application.ThreadException can be assigned an event handler to handle exceptions at application level.

Using ThreadPool:
ThreadPool class maintains some minimum no. of Threads to do work. One can queue his own work item. One can also set minimum and maximum no. of thread using SetMinThreads and SetMaxThreads.

ThreadPool static methods are:
GetAvailableThreads(# no of Threads), GetMaxThreads, GetMinThreads, QueueUserWorkItem, RegisterWaitForSingleObject, SetMinThreads, SetMaxThreads, UnsafeQueueNativeOverlapped, UnsafeQueueUserWorkItem, UnsafeRegisterWitForSingleObject. Unsafe methods do not propagate execution context info thus provide performance on cost of security.

WaitHandle and ThreadPool:
If we want to queue work item and we want that until a Mutex/Semaphore is not available. The work should not get started.

Mutex m = new Mutex (true);

ThreadPool.RegisterWaitForSingleObject(M, new WaitOrTimerCallback(MyWorkItem), null, Timeout.Infite, true);

m.ReleaseMutex(); //Now Work will start

The Synchronization Context:
It provides a middle way to resolve difference between threading model of windows application and Web Application. One can call:

SynchronizationContext.Send(RunMe, “Hello”);
OR
SynchronizationContext.Post(RunMe, “Hello”);

Post returns immediately but Send does not.

Timers: (System.Threading.Timer)
Timers call a method after specified time defined by TimerCallback delegate.

Timer tm = new Timer ( new TimerCallback(TimerTick), null, 0, 1000);

Static void TimerTick(object state)
{
                Console.WriteLine(“Tick Tick…”);
}

On can also call Timer(tm).Change to specify when timer start firing and Timer(tm).Change(Timeout.Infinite, 1000) to stop timer.

Other timer classes are System.Windows.Forms.Timer
And                                        System.Timers.Timer.

Comments

Popular posts from this blog

Culture Information and Localization in .NET

Namespace: System.Globalization CultureInfo Class:                 It provides information like the Format of numbers and dates, Culture’s Calendar, Culture’s language and sublanguage (if applicable), Country and region of the culture. The Basic use of CultureInfo class is shown here: • How string Comparisons are performed • How Number Comparison & Formats are performed • Date Comparison and Formats. • How resources are retrieved and used. Cultures are grouped into three categories: Invariant Culture : It’s Culture Insensitive. It can be used to build some trial application. It can be also used to build an application with hard-coded expiry date that ignores cultures. But using it for every comparison will be incorrect and inappropriate. Neutral Culture : English(en), Frensh(fr), and Spanish(sp). A neutral culture is related to language but it’s not related to specific regi...

Concept of App Domain in .Net

Creating Application Domains: Application domain is just like process, provides separate memory space, and isolates from other code. But it’s quite light weight. It also provides the following advantages: 1-       Reliability : If a domain crashes, it can be unloaded. Hence doesn’t affect the other assemblies. 2-       Efficiency : Loading all assemblies in one domain can be cumbersome and can make the process heavy but Appdomains are efficient in this manner. Important properties of AppDomain: ApplicationIdentity , ApplicationTrust , BaseDirectory , CurrentDomain , DomainManager , DomainDirectory , Evidence , FriendlyName , ID , RelativeSearchPath , SetupInformation , ShadowCopyFiles . Important methods of AppDomain: ApplyPolicy , CreateCOMInstanceFrom , CreateDomain , CreateInstance (Assembly). To create an AppDomain: AppDomain adomain = AppDomain.CreateDomain(“D”); To execute an assembly:...

Asynchronous Execution in ASP.NET

Asynchronous Execution: Two ways either implement IHTTPAsyncHandler interface or in ASP.NET 2.0 set <%@ Page Async=”true” %>. The second option implements IHTTPAsyncHandler interface automatically for the page when parsed or compiled. AddOnPreRenderCompleteAsync ( new BeginEventHandler(BeginTask), new EndEventHandler(EndTask)); AddOnPreRenderCompleteAsync() shoud be called in Page_load. The BeginEventHandler and EndEventHandler are delegates defined as follows: IAsyncResult BeginEventHandler( object sender, EventArgs e, AsyncCallback cb, object state) void EndEventHandler( IAsyncResult ar) AsyncProcess starts and completes between PreRender and PreRenderComplete. Other way to perform Async Task is using AsyncPageTask structure. It also allows multiple tasks to execute simultaneously. void Page_Load (object sender, EventArgs e) { PageAsyncTask task = new PageAsyncTask( new BeginEventHandler(BeginTask), new EndEventH...