I have a problem understanding why the rest of the function after using async is done in different threads for the same code. Take an example - in CODE 1 the rest of the RunClick function is executed in thread 3, which is logical, because the DoAsyncWork function was executed in it.
In the case of CODE 2, the rest of the btnCallMethod_Click function is still executed in thread 1., although the function DoWorkAsync was done in thread 3.
The only difference is that btnCallMethod_Click
is called from Windows Forms - it handles Click event for a standard button.
What does it depend on ? Does Windows Forms trigger events in any special way that the thread does not change?
//CODE 1:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp61
{
class Test
{
public event EventHandler Click;
public string TestString { get; set; }
internal void DoClick()
{
Click?.Invoke(this, new EventArgs());
}
public async void RunClick(object sender, EventArgs e)
{
Console.WriteLine("Before async call " + Thread.CurrentThread.ManagedThreadId); // Thread id=1
(sender as Test).TestString = await DoAsyncWork(1);
Console.WriteLine("After async call " + Thread.CurrentThread.ManagedThreadId); //Thread id=3 OK
}
private Task<string> DoAsyncWork(int step)
{
return Task.Run(() => {
Thread.Sleep(10000);
Console.WriteLine($"DoAsyncWork() " + Thread.CurrentThread.ManagedThreadId); //Thread id=3
return "555";
});
}
}
class Program
{
static async Task Main(string[] args)
{
Test x = new Test();
x.Click += x.RunClick;
x.DoClick();
Console.ReadKey();
}
}
}
/////////////////////////////////////////////////////////////////////
// CODE 2:
private async void btnCallMethod_Click(object sender, EventArgs e)
{
Console.WriteLine("step 1-" + Thread.CurrentThread.ManagedThreadId); //Thread id=1
this.Text = await DoWorkAsync();
Console.WriteLine("step 2-" + Thread.CurrentThread.ManagedThreadId); //Thread id=1 Still 1 !!! Why ? Should be 3
}
private async Task<string> DoWorkAsync()
{
return await Task.Run(() =>
{
Thread.Sleep(10000);
Console.WriteLine("step 99-" + Thread.CurrentThread.ManagedThreadId); // Thread id =3
return "Done with work!";
});
}