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();
}
1
  • Your question is completely answered by the documentation and by the marked duplicate. Commented Nov 5, 2017 at 20:02

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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?
What is the correct way to run an async method without await?
@ManosKanellopoulos: that's complicated (the simple case of using the Result property of Task<T> won't handle execution context (IIRC)). Hence: find the docs and read them.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.