0

我想创建将等到文档未加载的方法。

我有类似的东西:

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 并且没有任何反应。

4

2 回答 2

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");
于 2013-07-15T15:34:32.867 回答
0

您必须让 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;
    }
}
于 2013-07-15T13:18:01.850 回答