1
\$\begingroup\$

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;
}
\$\endgroup\$
3
  • 1
    \$\begingroup\$ _ exceeded the limit of characters for the day? ;-) This is a great name for a variable. \$\endgroup\$
    – t3chb0t
    Commented Jul 11, 2017 at 20:09
  • \$\begingroup\$ @t3chb0t lol :D, i like naming variables that way sometimes, although i know it's not a good practice, yet i consider the SemaphoreSlim pretty much self explanatory itself therefore i named it that way, same for the TaskCompletionSource. \$\endgroup\$ Commented Jul 11, 2017 at 20:24
  • \$\begingroup\$ Although in C# 7.0 _ on it's own means a discard, if you use a variable with that name then you can't use a discard, for example in as an out variable you don't want to use \$\endgroup\$ Commented Jul 12, 2017 at 9:32

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.