C# - 四模式在异步执行 [英] C# -Four Patterns in Asynchronous execution

查看:110
本文介绍了C# - 四模式在异步执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I heard that there are four patterns in asynchronous execution .

有四种模式在异步执行委托:轮询,等待完成,完成通知和射后不理

当我有以下的code:

When I have the following code :

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)什么是上面code实现的模式?

1) What is the pattern the above code implemented ?

2)你能解释一下code,我怎么能实现其余..?

2) Can you explain the code ,how can i implement the rest ..?

推荐答案

您有什么还有就是轮询模式。在这种模式中,你不断地问:我们到了没?在,而循环是做阻塞。在 Thread.sleep代码 prevents吃CPU周期的过程。

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...");

因此​​,一旦的WaitOne 是叫你正在阻塞,直到攀爬完成。您可以阻塞之前执行其他任务。

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...");
}

这里没有阻止,因为回调将被通知。


和射后不理会

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."

这篇关于C# - 四模式在异步执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆