Async await has different behavior in Win Forms and in my Console App. For the given sample code the output will looks like this:
Line 1: 1
Line 2: 1
Line 3: 1
Line 4: 1
Line 5: 1
Insde the Task: 3
After await: 3
But if I will run similar functions in WinForms on_button_click function I will get this result:
Line 1: 1
Line 2: 1
Line 3: 1
Line 4: 1
Line 5: 1
Insde the Task: 3
After await: 1 // HERE'S THE DIFFERENCE, after await thread 1 will continue instead of thread 3
That difference in WinForms is significant because thanks to this I will not receive Exception for modifying form outside of dispatcher thread. My question is, how can I achieve same behavior in my console application?
class Program
{
public async void methodAsync()
{
Trace.WriteLine("Line 2: " + currentThread());
await method();
Trace.WriteLine("After await: " + currentThread());
}
public Task method()
{
Trace.WriteLine("Line 3: " + currentThread());
Task t = new Task(() =>
{
Trace.WriteLine("Insde the Task: " + currentThread());
});
t.Start();
Trace.WriteLine("Line 4: " + currentThread());
return t;
}
public string currentThread()
{
return System.Threading.Thread.CurrentThread.ManagedThreadId.ToString();
}
public void test()
{
Trace.WriteLine("Line 1: " + currentThread());
methodAsync();
Trace.WriteLine("Line 5: " + currentThread());
System.Threading.Thread.Sleep(2000);
}
static void Main(string[] args)
{
Program p = new Program();
p.test();
}