C#-异步执行中的四种模式

标签 c# asynchronous execution

听说异步执行有四种模式。

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/

相关文章:

javascript - indexedDB idb 库 - 插入多条记录

python - 停止一个正在另一个 Python 脚本中运行的脚本

c# - 如何在 linq 中重现 MySQL 语句

实现相同属性的 C# 类

c#递归检查是否偶数

javascript - NodeJS - 给定目录的完整路径,如何异步获取所有子目录的列表并检查文件是否存在?

c# - 标记仅返回具有条件属性的任务的异步方法?

algorithm - 什么是好的(半)异步算法?

执行存储在数据段中的 x86 指令的性能损失?

c# - 如何比较 .NET 中的执行路径?