和新任务之间的差异

和新任务之间的差异

本文介绍了Task.Delay()和新任务之间的差异(()=> Thread.sleep()方法)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我组建了一个小一点的演示采取了 Thread.sleep代码()模拟长时间运行的方法,并想增加异步轻松地从一个同步的过程中去一个异步的。这里的初始code:

I was putting together a small little demo to take a long running method simulated with a Thread.Sleep() and wanted to add async to easily go from a synchronous process to an async one. Here's the initial code:

private void button1_Click(object sender, EventArgs e)
{
    LongProcess();
}

private void LongProcess()
{
    for (int i = 0; i < 33; i++)
    {
        progressBar1.Value += 3;
        Thread.Sleep(1000);
    }
    progressBar1.Value += 1;
}

我想我可以简单地改变 Thread.sleep代码(1000)新建任务(()=&GT; Thread.sleep代码( 1000)),就像这样:

private void button1_Click(object sender, EventArgs e)
{
    LongProcess();
}

private async void LongProcess()
{
    for (int i = 0; i < 33; i++)
    {
        progressBar1.Value += 3;
        await new Task(()=>Thread.Sleep(1000));
    }
    progressBar1.Value += 1;
}

然而,这永远不会返回到第一的await后循环。如果我改变Thread.sleep代码为Task.Delay一切正常,但我不明白为什么我的code不起作用。我假设的东西是越来越永远受阻,但它并不完全意义。任何人都可以解释我的code如何工作的,并没有改变,以Task.Delay(只是这样我就可以了解其工作原理另一个角度来看)?一个可能的解决方案

However this never returns to the loop after the first await. If I change the Thread.Sleep to a Task.Delay everything works, but I don't understand why my code doesn't work. I assume something is getting blocked forever, but it doesn't quite make sense. Can anyone explain how my code works, and a possible solution without changing to Task.Delay (just so I can get another perspective of how this works)?

推荐答案

Task.Delay 不一样盯着任务与主题。睡眠 Task.Delay 使用定时内部,因此它不会阻止任何线程,但是开始一个新的任务 Thread.sleep代码阻止该线程(通常线程池线程)。

Task.Delay isn't same as staring a Task with Thread.Sleep. Task.Delay uses Timer internally and thus it doesn't blocks any thread, however starting a new Task with Thread.Sleep blocks the thread (typically Threadpool thread).

在你的榜样,你永远不启动工作。创建一个工作与构造函数会返回一个未开始任务需要与呼叫启动开始方法。否则,将永远不会完成(因为你永远不启动它)。

In your example you never started the Task. Creating a Task with constructor will return a Unstarted task needs to be started with a call to Start method. Otherwise it will never complete(because you never started it).

但是致电 Task.Start 气馁,你可以叫 Task.Factory.StartNew(()=&GT; Thread.sleep代码(1000) ) Task.Run(()=&GT; Thread.sleep代码(1000))如果你想为浪费资源

However calling Task.Start is discouraged, You can call Task.Factory.StartNew(()=> Thread.Sleep(1000)) or Task.Run(()=> Thread.Sleep(1000)) if you want to waste a resource.

此外,要知道,,则应该preFER Task.Run StartNew ,除非有令人信服的理由这样做。

Also, be aware that StartNew is dangerous, you should prefer Task.Run over StartNew unless there's a compelling reason to do so.

这篇关于Task.Delay()和新任务之间的差异(()=&GT; Thread.sleep()方法)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 23:17