gpt4 book ai didi

c# - Task.ContinueWith 无法正常工作

转载 作者:太空狗 更新时间:2023-10-29 22:11:10 27 4
gpt4 key购买 nike

考虑以下代码。我从一个不执行任何操作的任务开始,然后使用 ContinueWith() 开始调用 10 次递增计数器的方法。

当我运行这个程序时,它打印“0”,表示根本没有调用 increment() 方法。我预计它会被调用 10 次,因为那是我调用 ContinueWith() 的次数。

如果我取消注释“Thread.Sleep(20)”行,那么它会按预期打印“10”。

这发生在发布或 Debug模式中。我的系统是运行 Windows 7 x64 的具有超线程(8 个逻辑内核)的核心 2 四核。

我假设我对 Task.ContinueWith() 的工作原理存在某种根本性的误解....

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication4
{
class Program
{
static void Main()
{
using (var task = Task.Factory.StartNew(()=>{}))
{
for (int i = 0; i < 10; ++i)
{
task.ContinueWith(_=> increment());
// Thread.Sleep(20); // Uncomment to print 10 instead of 0.
}

task.Wait();
}

// This prints 0 UNLESS you uncomment the sleep above.
Console.WriteLine(counter);
}

static void increment()
{
Interlocked.Increment(ref counter);
}

private static int counter;
}
}

任何人都可以阐明这里发生了什么吗?

最佳答案

原因很简单:您等待已经完成的任务。你真正想要的是等待你在循环中创建的十个任务:

var tasks = new List<Task>();
for (int i = 0; i < 10; ++i)
{
tasks.Add(task.ContinueWith(_=> increment()));
}

Task.WaitAll(tasks.ToArray());

关于c# - Task.ContinueWith 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6997480/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com