【发布时间】:2018-04-17 09:23:01
【问题描述】:
我正在尝试使用System.Threading.Tasks.Task 类实现并行处理。奇怪的是,任务委托的执行在第一次方法调用时就停止了。我在下面的示例代码中编码以重新创建问题。
using System;
using System.Threading.Tasks;
namespace TestApp
{
public static class TestClass
{
static TestClass()
{
var tasks = new Task[Environment.ProcessorCount];
for (int i = 0; i < Environment.ProcessorCount; i++)
{
var task = Task.Run(() =>
{
Console.WriteLine("Start the Task " + i);
// Method Foo is not called.
// Stack trace show a managed to native transition.
// Why?
Foo(i);
});
tasks[i] = task;
}
Task.WaitAll(tasks);
Console.WriteLine("Press eny key to exit");
Console.ReadKey();
}
private static void Foo(int i)
{
Console.WriteLine("Foo in the Task " + i);
}
}
}
我调用方法TestClass.Bar() 来调用TestClass 的静态构造函数。
主线程按预期在Task.WaitAll(tasks) 调用处等待并行任务。但它永远不会完成,因为任务本身卡在 Foo 方法调用中。
其中一项卡住任务的堆栈跟踪:
TestApp.exe!TestApp.TestClass..cctor.AnonymousMethod__0
[Managed to Native Transition]
TestApp.exe!TestApp.TestClass..cctor.AnonymousMethod__0() Line 18
mscorlib.dll!System.Threading.Tasks.Task.InnerInvoke()
mscorlib.dll!System.Threading.Tasks.Task.Execute()
mscorlib.dll!System.Threading.Tasks.Task.ExecutionContextCallback(object obj)
mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx)
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx)
mscorlib.dll!System.Threading.Tasks.Task.ExecuteWithThreadLocal(ref System.Threading.Tasks.Task currentTaskSlot)
mscorlib.dll!System.Threading.Tasks.Task.ExecuteEntry(bool bPreventDoubleExecution)
mscorlib.dll!System.Threading.Tasks.Task.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
mscorlib.dll!System.Threading.ThreadPoolWorkQueue.Dispatch()
mscorlib.dll!System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
有人能指出为什么 Foo 方法没有被调用吗?
【问题讨论】:
-
呃,
Console.WriteLine可以在多线程上运行吗? -
@BagusTesa 是的。
-
这段代码可以正常运行(除了
i值未被捕获)
标签: c# .net parallel-processing task .net-4.6.2