I'm trying to run some stuff asynchronous. Here's my code:
private async void SearchButton_Click(object sender, EventArgs e)
{
await Search();
}
// Inside search there is no async operation
public Task Search()
{
// search for data in DB
// update DataGridView and other elements on UI
// How to return null/void/nothing?
return ???;
}
Is it illegal/bad practice to await on synchronous methods like Search()
? I know I can use Task.Run(Search)
instead but then Search()
will be executed on another thread (not on UI thread) and I have to use Invoke()
inside Search()
very often.
I changed the return value of Search()
method from 'void' to 'Task' so its awaitable but what do I have to return?
Is it illegal/bad practice to await on synchronous methods like Search()?
Well it's a very bad idea, because your UI will hang, basically.
You should change your Search
method to SearchAsync
(for the sake of convention) and use asynchronous database operations to make it properly asynchronous.
Currently, you don't have any true asynchrony: everything will just happen on your UI thread.
See more on this question at Stackoverflow