C# -Four Patterns in Asynchronous execution

拟墨画扇 提交于 2019-11-27 16:49:35

What you have there is the Polling pattern. In this pattern you continually ask "Are we there yet?" The while loop is doing the blocking. The Thread.Sleep prevents the process from eating up CPU cycles.


Wait for Completion is the "I'll call you" approach.

IAsyncResult ar = data.BeginInvoke(null, null);
//wait until processing is done with WaitOne
//you can do other actions before this if needed
ar.AsyncWaitHandle.WaitOne(); 
Console.WriteLine("..Climbing is completed...");

So as soon as WaitOne is called you are blocking until climbing is complete. You can perform other tasks before blocking.


With Completion Notification you are saying "You call me, I won't call you."

IAsyncResult ar = data.BeginInvoke(Callback, null);

//Automatically gets called after climbing is complete because we specified this
//in the call to BeginInvoke
public static void Callback(IAsyncResult result) {
    Console.WriteLine("..Climbing is completed...");
}

There is no blocking here because Callback is going to be notified.


And fire and forget would be

data.BeginInvoke(null, null);
//don't care about result

There is also no blocking here because you don't care when climbing is finished. As the name suggests, you forget about it. You are saying "Don't call me, I won't call you, but still, don't call me."

Chris Cudmore
while (!ar.IsCompleted)
{
    Console.WriteLine("...Climbing yet to be completed.....");
    Thread.Sleep(200);
}

That's classic polling. - Check, sleep, check again,

This code is Polling:

while (!ar.IsCompleted)

That's the key, you keep checking whether or not it's completed.

THis code doesn't really support all four, but some code does.

Process fileProcess = new Process();
// Fill the start info
bool started = fileProcess.Start();

The "Start" method is Asynchronous. It spawns a new process.

We could do each of the ways you request with this code:

// Fire and forget
// We don't do anything, because we've started the process, and we don't care about it

// Completion Notification
fileProcess.Exited += new EventHandler(fileProcess_Exited);

// Polling
while (fileProcess.HasExited)
{

}

// Wait for completion
fileProcess.WaitForExit();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!