Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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:

  1. Not blocking the GUI thread
  2. Being able to call the ApplySomethingOnTheGuiBasedOnTheResult after my async method has been called
  3. 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
224 views
Welcome To Ask or Share your Answers For Others

1 Answer

You simply need to mark your handler as async:

public async void OnSomething(SomeEventArgs args)
{
    SomeResult result = await _businessObject.AsyncCall();
    ApplySomethingOnTheGuiBasedOnTheResult(result);
}

I know it's not recommended to use asyc with return type void (normally it should be Task or Task<sometype>), but if the event requires that signature, it's the only way.

This way the control flow is returned to the caller at the await statement. When the AsyncCall has finished, execution is eventually resumed after the await on the UI thread.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...