微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决C# - 异步执行的四种模式

你所拥有的是轮询模式。在这种模式下,你不断地问“我们到了吗?” 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

这里也没有阻塞,因为您不在乎攀登何时完成。顾名思义,你忘了它。你是在说“不要打电话给我,我不会打电话给你,但是,不要打电话给我。”

解决方法

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

异步委托执行有四种模式:轮询、等待完成、完成通知和“一劳永逸”

当我有以下代码时:

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)你能解释一下代码吗,我怎样才能实现其余的..?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。