Trying to wrap my head around TaskCompletionSource
. Here is a little class I wrote to synchronously (WebBrowser.Navigate()
is async) download a webpage and return it to the caller. I'm not sure if I have used TaskCompletionSource
correctly. Can someone please indicate what I'm missing here, or if this is entirely an over-engineered solution?
class PageDownloader
{
private WebBrowser _WB = new WebBrowser();
private TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
public PageDownloader()
{
_WB.LoadCompleted += _WB_LoadCompleted;
}
public string Download(string url)
{
_WB.Navigate(new Uri(url));
tcs.Task.Wait();
if (tcs.Task.IsCanceled || tcs.Task.IsFaulted)
return null;
else
return (_WB.Document as mshtml.HTMLDocument).body.innerHTML;
}
private void _WB_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
var docTemp = _WB.Document as mshtml.HTMLDocument;
foreach (mshtml.IHTMLImgElement imgElemt in docTemp.images)
imgElemt.src = "";
tcs.SetResult(true);
}
}