-1

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){
    //.....
}
Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
K.Z
  • 5,201
  • 25
  • 104
  • 240
  • 1
    what does not work exactly? – sommmen Mar 22 '22 at 07:51
  • 1
    The `Thread` constructor does not understand async delegates. You can read about this [here](https://stackoverflow.com/questions/44364092/is-it-ok-to-use-async-with-a-threadstart-method) or [here](https://stackoverflow.com/questions/30044846/async-thread-body-loop-it-just-works-but-how). – Theodor Zoulias Mar 22 '22 at 08:05

1 Answers1

3

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
Enigmativity
  • 113,464
  • 11
  • 89
  • 172