0

I have a third-party library which all methods are async and I have some questions

1) What is the difference between these two code lines?

Task.Run(async () => await MethodAsync());
Task.Run(() => PrepareDashBoard());

2) When I need to call an async method from an button click event which one is right?

// A.
private void Button_Click(object sender, EventArgs e)
{
  //A Task Run call from questions 1) a or b with call to Wait or Result (if return something)
}

// B
private async void Button_Click(object sender, EventArgs e) 
{
  await MethodAsync();
}
Richard
  • 106,783
  • 21
  • 203
  • 265

1 Answers1

1

TL;DR: Until you understand the implications do not mix directly using the task parallel library (Task<T> etc) with async and await (other than in the definition of async function return types).

To call an async function without a WinForms even handler just use

var res = await theFunction(args);

The WinForms runtime knows how to handle the thread management (so all GUI interactions stay on one thread).

Re. Q1:

a. Launches a new asynchronous task to call an async method asynchronously and is complete when the inner task starts running. This is extremely unlikely to be what you want.

b. Runs the lambda in an asynchronous task, the task is marked complete when the lambda completes.

PS. When C#5 was launched there were many articles covering the interaction of async and WinForms in far greater detail than is possible in an answer here.

VMAtm
  • 27,943
  • 17
  • 79
  • 125
Richard
  • 106,783
  • 21
  • 203
  • 265
  • A correction in first question about what is the difference between these two code lines? the code lines are `Task.Run(async () => await MethodAsync());` `Task.Run(() => PrepareDashBoard());` And if I understand correcty you told me that I must do not mix directly using Task.Run with async and wait? – Manos Kanellopoulos Nov 05 '17 at 16:29
  • What is the correct way to run an async method without await? – Manos Kanellopoulos Nov 05 '17 at 16:34
  • @ManosKanellopoulos: that's complicated (the simple case of using the `Result` property of `Task` won't handle execution context (IIRC)). Hence: find the docs and read them. – Richard Nov 05 '17 at 17:18