我创建了 2 个线程,但没有得到结果

I created 2 threads but I don't get result

我正在处理 .NET CORE 3.1 应用程序。我有两种类型的记录对象,它们调用相同的方法来处理数据并在 return 中添加到相同的列表。我将代码从经典循环修改为线程。所以我创建了两个线程和 objective 我可以提高性能但是如果我 运行 两个线程我没有得到结果但是如果我只做一个线程然后它工作并得到结果......不是确定我从拼图中遗漏了什么。

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,它们就会 return 控制调用代码 - 因此 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