I've an event on an UserControl(winform) that I'm listening:
public void OnSomething(SomeEventArgs args){
SomeResult result = ?await? _businessObject.AsyncCall();
ApplySomethingOnTheGuiBasedOnTheResult(result);
}
_businessObject.AsyncCall()
has the following signature:
public async Task<SomeResult> AsyncCall();
How can I call this async method while:
- Not blocking the GUI thread
- Being able to call the
ApplySomethingOnTheGuiBasedOnTheResult
after my async method has been called - Being able to call the
ApplySomethingOnTheGuiBasedOnTheResult
in the correct(GUI) thread.
What I tried:
public void OnSomething(SomeEventArgs args){
SomeResult result = await _businessObject.AsyncCall();
ApplySomethingOnTheGuiBasedOnTheResult(result);
}
--> Doesn't compile since my event handler isn't async.
public void OnSomething(SomeEventArgs args){
SomeResult result = _businessObject.AsyncCall().Result;
ApplySomethingOnTheGuiBasedOnTheResult(result);
}
--> The application freeze
public void OnSomething(SomeEventArgs args){
_businessObject.AsyncCall().ContinueWith(t=>{
if(InvokeRequired){
Invoke(new Action(()=>ApplySomethingOnTheGuiBasedOnTheResult(t.Result)));
}
});
}
--> Works, but I was hopping that there was a nicer way to do it with the async/await.
See Question&Answers more detail:os