浏览器-正在等待文档加载
本文关键字:文档 加载 在等待 浏览器 | 更新日期: 2023-09-27 18:22:25
我想创建一个方法,该方法将等待文档未加载。
我有这样的东西:
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
中,它正在阻止Navigate,但什么也没发生。
您可以使用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");
您必须让UI线程保持原样,并在加载完成后禁用表单并启用
用法
MyClient client = new MyClient(webBrowser,
() => { client.NotImplemented(); //i'm already logged; }
);
client.LogIn("test", "omg"); //block thread
隐含
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;
}
}