async method with completed event

前端 未结 2 995
抹茶落季
抹茶落季 2020-12-30 12:21

I use .net 4.0 and i\'ve tried to figure out how to use async method to await DocumentCompleted event to complete and return the value. My original code is above, how can i

2条回答
  •  攒了一身酷
    2020-12-30 12:42

    So we need a method that returns a task when the DocumentCompleted event fires. Anytime you need that for a given event you can create a method like this:

    public static Task WhenDocumentCompleted(this WebBrowser browser)
    {
        var tcs = new TaskCompletionSource();
        browser.DocumentCompleted += (s, args) => tcs.SetResult(true);
        return tcs.Task;
    }
    

    Once you have that you can use:

    await browser.WhenDocumentCompleted();
    

提交回复
热议问题