The return value of an async function is Task instead of void and Task<TResult> instead of TResult.
If you change your function into the following it will be correct:
private static async Task Run()
{
...
await ...
}
There is one exception, an async event handler may return void:
private async void OnButton1_clicked(object sender, ...)
{
await Run();
}
This is enough to keep your UI responsive while the task is running.
- You can only use await in a function if your function is async
- async functions return Task instead of void and Task
<TResult> instead of TResult.
- the value of await Task
<TResult>, is TResult.
- only async functions can all other async functions.
If you have a non-async function and you want to start a task while doing other things, you can use the following code:
private void MyFunction()
{
// do some processing
// start a separate task, don't wait for it to finish:
var myTask = Task.Run( () => MyAsyncFunction(...))
// while the task is running you can do other things
// after a while you need the result:
TResult result = await myTask;
ProcessResult(result);
}
You can even start several tasks, and while they are processing do other things and after a while wait for the tasks to finish:
private async void OnButton1_clicked(object sender, ...)
{
var Tasks = new List<Task>();
for (int i=0; i<10; ++i)
{
Tasks.Add(Run());
}
// while all tasks are scheduled to run, do other things
// after a while you need the result:
await Task.WhenAll(tasks);
// Task.WhenAll(...) returns a Task, so await Task.WhenAll returns void
// async functions that return Task`<TResult`> has a Result property
// that has the TResult value when the task if finished:
foreach (var task in tasks)
{
ProcessResult(task.Result);
}
// not valid for your Run(), because that had a Task return value.
}
GetDataAsyncis returning a task, however,Runis not.async voidshould only be used for event handlers. - John Koerner