我想创建一个等待文档加载的方法。
我有类似的东西:
WebBrowser webBrowser = new WebBrowser();
MyClient client = new MyClient(webBrowser);
client.LogIn("test", "omg"); //block thread
client.NotImplemented(); //i'm already logged;
class MyClient
{
bool Started;
WebBrowser webBrowser;
public MyClient(WebBrowser wb)
{
webBrowser = wb;
webBrowser.DocumentCompleted += (sender, e) =>
{
if (e.Url == webBrowser.Url)
{
Started = false; //page loaded
}
};
}
public void LogIn(string login, string password)
{
this.Navigate("mymagicsite.com");
}
private void Navigate(string url)
{
webBrowser.Navigate(url);
Started = true;
while(Started)
Task.Delay(50);
}
}
当我将调用LogIn方法时,我想“阻止”我的线程。
问题出在Task.Delay
,它阻止导航,没有任何反应。
答案 0 :(得分:1)
您可以使用TaskCompletionSource
发送某个事件的async
- 兼容“通知”。
像这样:
class MyClient
{
TaskCompletionSource<object> navigation;
WebBrowser webBrowser;
public MyClient(WebBrowser wb)
{
navigation = new TaskCompletionSource<object>();
webBrowser = wb;
webBrowser.DocumentCompleted += (sender, e) =>
{
if (e.Url == webBrowser.Url)
{
navigation.TrySetCompleted(null);
}
};
}
public Task LogIn(string login, string password)
{
navigation = new TaskCompletionSource<object>();
webBrowser.Navigate(url);
return navigation.Task;
}
}
可以这样使用:
WebBrowser webBrowser = new WebBrowser();
MyClient client = new MyClient(webBrowser);
await client.LogIn("test", "omg");
答案 1 :(得分:0)
你必须离开UI线程,然后禁用表单,并在加载完成后启用
用法
MyClient client = new MyClient(webBrowser,
() => { client.NotImplemented(); //i'm already logged; }
);
client.LogIn("test", "omg"); //block thread
Implemation
class MyClient
{
Form frm;
public MyClient(WebBrowser wb, MethodInvoker callback)
{
frm = (Form) wb.Parent; // assume WebBrowser is directly on the form
webBrowser = wb;
webBrowser.DocumentCompleted += (sender, e) =>
{
frm.Invoke( new MethodInvoker( () => frm.Enabled = true ));
frm.Invoke(callback);
};
}
private void Navigate(string url)
{
webBrowser.Navigate(url);
frm.Enabled = false;
}
}