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

Longtime reader, first-time poster here.

My goal: To be able to take advantage of async/await while using the WebBrowser class. As the WebBrowser.Navigate(string url) is an asynchronous method, and you can't examine the html document until the LoadComplete event is fired.

Here is my (working) code so far:

public class AsyncWebBrowser
{
    protected WebBrowser m_WebBrowser;

    private ManualResetEvent m_MRE = new ManualResetEvent(false);

    public void SetBrowser(WebBrowser browser) {
        this.m_WebBrowser = browser;
        browser.LoadCompleted += new LoadCompletedEventHandler(WebBrowser_LoadCompleted);
    }

    public Task NavigateAsync(string url) {
        Navigate(url);

        return Task.Factory.StartNew((Action)(() => {
            m_MRE.WaitOne();
            m_MRE.Reset();
        }));
    }

    public void Navigate(string url) {
        m_WebBrowser.Navigate(new Uri(url));
    }

    void WebBrowser_LoadCompleted(object sender, NavigationEventArgs e) {
        m_MRE.Set();
    }
}

And this previous class now allows me to use the following:

public async void NavigateToGoogle() {
    await browser.NavigateAsync("www.google.com");
    //Do any necessary actions on google.com
}

However, I am wondering if there is a more efficient/proper way of handling this. Specifically, the Task.Factory.CreateNew with the blocking ManualResetEvent. Thanks for your input!

See Question&Answers more detail:os

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

1 Answer

First off, I think this is a great exercise for learning how async/await works.

You seem to be jumping through hoops in order to make NavigateAsync return a Task. But it doesn't have to return a Task in order to be awaitable! A method that contains an await must return Task, but a method that is awaitable need not return Task; all it has to do is return some type that you can call GetAwaiter on.

You might consider implementing a little type like this:

public struct WebBrowserAwaiter<T>
{
    public bool IsCompleted { get { ... } }
    public void OnCompleted(Action continuation) { ... }
    public T GetResult() { ... }
}

and have NavigateAsync return some type upon which you can call GetAwaiter that returns a WebBrowserAwaiter. No need to build up a Task just to get its GetAwaiter method when you can make your own.

More generally, something you might want to give some thought to is what happens if there is a second call to NavigateAsync while the first one is still navigating?


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