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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1784928/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 20:47:57  来源:igfitidea点击:

C# -Four Patterns in Asynchronous execution

c#asynchronousexecution

提问by user215675

I heard that there are four patterns in asynchronous execution.

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

There are four patterns in async delegate execution: Polling, Waiting for Completion, Completion Notification, and "Fire and Forget"

异步委托执行有四种模式:轮询、等待完成、完成通知和“即发即弃”

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) What is the pattern the above code implemented ?

1) 上面代码实现的模式是什么?

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

2)你能解释一下代码,我该如何实现其余的..?

采纳答案by Bob

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

您拥有的是轮询模式。在这种模式中,你不断地问“我们到了吗?” 该while循环是做阻塞。这Thread.Sleep可以防止进程占用 CPU 周期。



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 WaitOneis called you are blocking until climbing is complete. You can perform other tasks before blocking.

因此,一旦WaitOne被调用,您就会阻塞,直到攀爬完成。您可以在阻塞之前执行其他任务。



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 Callbackis going to be notified.

这里没有阻塞,因为Callback会被通知。



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

这里也没有阻塞,因为你不在乎攀登结束。顾名思义,你忘记了它。你是在说“别给我打电话,我不会给你打电话,但还是不要给我打电话。”

回答by McKay

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.

“Start”方法是异步的。它产生了一个新的进程。

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();

回答by Chris Cudmore

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

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

这是经典的投票。- 检查,睡觉,再检查,