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;
}
_
exceeded the limit of characters for the day? ;-) This is a great name for a variable. \$\endgroup\$