听说异步执行有四种模式。
There are four patterns in async delegate execution: Polling, Waiting for Completion, Completion Notification, and "Fire and Forget"
当我有以下代码时:
class AsynchronousDemo
{
public static int numberofFeets = 0;
public delegate long StatisticalData();
static void Main()
{
StatisticalData data = ClimbSmallHill;
IAsyncResult ar = data.BeginInvoke(null, null);
while (!ar.IsCompleted)
{
Console.WriteLine("...Climbing yet to be completed.....");
Thread.Sleep(200);
}
Console.WriteLine("..Climbing is completed...");
Console.WriteLine("... Time Taken for climbing ....{0}",
data.EndInvoke(ar).ToString()+"..Seconds");
Console.ReadKey(true);
}
static long ClimbSmallHill()
{
var sw = Stopwatch.StartNew();
while (numberofFeets <= 10000)
{
numberofFeets = numberofFeets + 100;
Thread.Sleep(10);
}
sw.Stop();
return sw.ElapsedMilliseconds;
}
}
1) 上述代码实现的模式是什么?
2) 你能解释一下代码吗,我该如何实现其余的..?
最佳答案
您拥有的是轮询模式。在这种模式下,您会不断地问“我们到了吗?” while
循环正在执行阻塞。 Thread.Sleep
可防止进程耗尽 CPU 周期。
等待完成是“我会调用你”的方法。
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...");
因此,一旦调用 WaitOne
,您就会阻塞,直到爬升完成。您可以在阻止之前执行其他任务。
有了完成通知,你就在说“你给我打电话,我不会给你打电话。”
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...");
}
这里没有阻塞,因为 Callback
将被通知。
火了就忘了
data.BeginInvoke(null, null);
//don't care about result
这里也没有阻塞,因为你不关心爬升什么时候结束。顾名思义,你忘了它。你在说“别给我打电话,我不会给你打电话,但还是不要给我打电话。”
关于C#-异步执行中的四种模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1784928/