Reputation: 31813
I want a method like this:
public async void DoSomething()
{
DoSomethingElse();
}
But because there is no AWAIT I get a warning that it will run synchronously. That was not my intent. My intent was to run async. So, I do this:
public async void DoSomething()
{
await Task.Delay(0);
DoSomethingElse();
}
This works. But is this cheating or something?
Upvotes: 2
Views: 251
Reputation: 564413
If you want to make the method run asynchronously, you'd typically write it like:
public Task DoSomething()
{
return Task.Factory.StartNew( () => DoSomethingElse());
}
This will cause the TPL to schedule your method to run (on a background thread), and allow the caller to use await
when they call your method if they need to use the async/await support.
Your current code doesn't actually cause this to run asynchronously - it causes the method to run and return immediately, but then schedule the DoSomethingElse()
to occur on the same synchronization context in which you're currently running. This means that, if you call your method on a UI thread, you'll immediately continue your previous code, and not block the UI right then, but will still block it later when the context execute the DoSomethingElse()
call.
This is, of course, assuming that DoSomethingElse()
is not itself an asynchronous method. If it's defined as Task DoSomethingElse()
, you could just write:
public async Task DoSomething()
{
// other code as needed
await DoSomethingElse();
// other code as needed
}
Upvotes: 4