简体   繁体   English

为什么在任务工厂中使用ASYNC-AWAIT?

[英]Why using ASYNC - AWAIT in task factory?

im new in task jobs and need to help. 我在任务工作中是新手,需要帮助。 I have a web service, 我有一个网络服务,

this service will stop all tasks and start again in every 30 mins. 该服务将停止所有任务,然后每30分钟重新启动一次。

Q1= Is that regular code sample ? Q1 =是常规代码示例吗?

Q2= This code works for me, but do i need ASYNC AWAIT in this project ? Q2 =该代码对我有用,但是我在该项目中需要ASYNC AWAIT吗? i'm using .net 4.0. 我正在使用.net 4.0。

Thx. 谢谢。

private CancellationTokenSource tokenSource;
private List<Task> Tasks;
public virtual void Start()
{
    // start
    Tasks = new List<Task>();
    tokenSource = new CancellationTokenSource();
    for (int i = 0; i < 3; i++)
    {
        Tasks.Add(Task.Factory.StartNew(() => SomeWork(),
                tokenSource.Token,
                TaskCreationOptions.LongRunning,
                TaskScheduler.Default));
    }
}

public void Stop()
{
    tokenSource.Cancel();
    Task.Factory.ContinueWhenAll(Tasks.ToArray(), t =>
    {
        Console.WriteLine("all finished");
        // start again
        Start();
    });
}

int i = 0;
public void SomeWork()
{
    while (!tokenSource.IsCancellationRequested)
    {
        try
        {
            Thread.Sleep(1000 * 4);
            Console.WriteLine(Task.CurrentId + " finised!");
        }
        catch (Exception) { }
    }
}

Do you really need to use the async/await keywords to be able to start and stop a task? 您是否真的需要使用async / await关键字来启动和停止任务? No. 没有。

Should you use the async/await keywords in your web service? 您是否应该在Web服务中使用async / await关键字? Not necessarily because you don't really seem to benefit much from being able to capture the context and execute the remainder of the method once a task has finisihed. 不一定,因为一旦完成任务,您似乎并不能从捕获上下文并执行方法的其余部分中受益。 Your Start method just fires off 3 tasks and return without waiting for any of the tasks to finish. 您的Start方法仅触发3个任务并返回,而无需等待任何任务完成。 So this method isn't really "awaitable" or asynchronous by nature. 因此,这种方法本质上并不是真正的“等待”或异步的。

You could have made use of the async/await keywords in your Stop method if you wanted to make it asynchronous, ie you wanted any caller of this method be able to call it asynchronously and do something once the tasks have actually been stopped: 可能已经利用异步的/在等待着您的停车方式的关键字,如果你想让它异步,即你想要这个方法的任何调用者能够异步调用它,只做一次的任务实际上已经停止:

public async Task StopAsync()
{
    tokenSource.Cancel();
    await Task.WhenAll(Tasks.ToArray());
    Console.WriteLine("all finished");
    Start();
}


await StopAsync();
//now all tasks have been stopped...do something

When using the async and await keywords the compiler basically generates a state machine for you. 使用async和await关键字时,编译器基本上会为您生成一个状态机。 The beginning of an async method is executed just like any other method and when it hits an "await" keyword it returns from the method and tells the awaitable (that is the asynchronous operation) to run the remainder of the method once it has completed. 异步方法的开始就像其他方法一样被执行,当它碰到“ await”关键字时,它将从该方法返回,并告诉awaitable(即异步操作)在方法完成后运行其余方法。 Please refer to the following link for more information about this. 请参考以下链接以获取更多信息。

How and When to use `async` and `await` 如何以及何时使用`async`和`await`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM