Skip to main content
4 of 4
edited tags
200_success
  • 144.2k
  • 22
  • 188
  • 473

Navigate a WebBrowser control asynchronously

I wrote a little method to navigate a WebBrowser control asynchronously and returns DocumentResult, yet i wanna know if this is a good approach for solving such problem.

Code

SemaphoreSlim _ = new SemaphoreSlim(1);

public async Task<string> NavigateAsync(string url, string targetFrameName = null, byte[] postData = null, string additionalHeaders = null, CancellationToken c = default(CancellationToken))
{
    await _.WaitAsync(c);

    var o = new TaskCompletionSource<string>(null);
    #pragma warning disable 4014
    Task.Factory.StartNew(() =>
    #pragma warning restore 4014
    {
        void OnDocumentCompleted(object x, WebBrowserDocumentCompletedEventArgs e)
        {
            if (e.Url.AbsolutePath != Url.AbsolutePath)
                return;

            DocumentCompleted -= OnDocumentCompleted;

            _.Release();
            o.SetResult(DocumentText);
        }

        Navigate(url, targetFrameName, postData, additionalHeaders);
        DocumentCompleted += OnDocumentCompleted;
    }, c);
    return await o.Task;
}