Home > Mobile >  I created 2 threads but I don't get result
I created 2 threads but I don't get result

Time:03-24

I am working on .NET CORE 3.1 applications. I have record object of two types which call same method to process data and in return add to same list. I modify code from classic loop to thread. so I created two threads and objective that I can improve performance however if I run both threads I don't get result but if I do just one thread then it do work and get result... not sure what I am missing from puzzle.

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();

Method that called by thread:

private async Task<List<Customers>> MethodX(Record r){
    //.....
}

CodePudding user response:

Try this code:

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");

It outputs:

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

Effectively the threads start and as soon as they hit an await they return control to the calling code - hence the Join completes - and after the delay is completed the code then continues.

Now try the same thing, but with tasks:

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");

That gives:

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
  • Related