我正在开发.NET CORE 3.1应用程序。我有两种类型的记录对象,它们调用相同的方法来处理数据,并返回到相同的列表中。我将代码从经典循环修改为线程。所以我创建了两个线程,目标是我可以提高性能,但是如果我运行两个线程我不会得到结果,但如果我只运行一个线程,它就会工作并得到结果。。。不确定我在这个谜题中遗漏了什么。
Thread processThreadA = new Thread(async () =>
{
var processedNonInbound= await MethodX(data);
returnList.AddRange(processedNonInbound);
});
Thread processThreadB = new Thread(async () =>
{
var processInbound = await MethodX(data);
returnList.AddRange(processInbound);
});
processThreadA.Start();
processThreadB.Start();
processThreadA.Join();
processThreadB.Join();
线程调用的方法:
private async Task<List<Customers>> MethodX(Record r){
//.....
}
试试这个代码:
Thread processThreadA = new Thread(async () =>
{
await Task.Delay(TimeSpan.FromSeconds(5.0));
Console.WriteLine($"{DateTime.Now} A");
});
Thread processThreadB = new Thread(async () =>
{
await Task.Delay(TimeSpan.FromSeconds(5.0));
Console.WriteLine($"{DateTime.Now} B");
});
processThreadA.Start();
processThreadB.Start();
Console.WriteLine($"{DateTime.Now} Started");
processThreadA.Join();
processThreadB.Join();
Console.WriteLine($"{DateTime.Now} Joined");
它输出:
2022/03/22 18:37:32 Started
2022/03/22 18:37:32 Joined
2022/03/22 18:37:37 B
2022/03/22 18:37:37 A
有效地,线程启动,一旦达到await
,它们就将控制权返回给调用代码——因此Join
完成了——延迟完成后,代码继续。
现在尝试同样的事情,但有任务:
Task processTaskA = Task.Run(async () =>
{
await Task.Delay(TimeSpan.FromSeconds(5.0));
Console.WriteLine($"{DateTime.Now} A");
});
Task processTaskB = Task.Run(async () =>
{
await Task.Delay(TimeSpan.FromSeconds(5.0));
Console.WriteLine($"{DateTime.Now} B");
});
Console.WriteLine($"{DateTime.Now} Started");
Task.WaitAll(processTaskA, processTaskB);
Console.WriteLine($"{DateTime.Now} Joined");
这就给出了:
2022/03/22 18:40:33 Started
2022/03/22 18:40:38 A
2022/03/22 18:40:38 B
2022/03/22 18:40:38 Joined