我正在开发一个 WinForms 应用程序,它将包含一个 WebBrowser
并将充当另一个进程的服务。我想实现一个 NavigateAndWait
方法,但显然,当我从客户端调用我的服务(我的 WinForms 应用程序)方法时,此方法在同一线程中运行或以某种方式与服务的 UI 同步线。这是我目前所拥有的:
服务:
public class Browser : IBrowser
{
private bool _Navigating = false;
public bool Navigating
{
get { return _Navigating; }
}
public Browser()
{
ServiceForm.Instance.webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
}
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if(e.Url == ServiceForm.Instance.webBrowser1.Url) _Navigating = false;
}
public void Navigate(string url)
{
_Navigating = true;
ServiceForm.Instance.webBrowser1.Navigate(url);
}
}
客户:
private void button1_Click(object sender, EventArgs e)
{
EndpointAddress endpointAddress = new EndpointAddress("net.pipe://localhost/PipeReverse/PipeReverse");
NetNamedPipeBinding pipeBinding = new NetNamedPipeBinding();
ChannelFactory<IBrowser> pipeFactory = new ChannelFactory<IBrowser>(pipeBinding, endpointAddress);
IBrowser browser = pipeFactory.CreateChannel();
browser.Navigate("http://www.google.com");
while (browser.Navigating) { }
MessageBox.Show("done!");
}
这工作正常,除了我的客户会卡住一会儿(字面意思!)。我可以轻松地在客户端的另一个线程上运行 button1_Click
,但我真正想做的是实现我的 NavigateAndWait
(这基本上是最后三行代码在我的服务中的 button1_Click
方法中)。但我已经尝试过了,但它永远不会返回,显然是因为 DocumentComplete
事件处理程序从未被调用,因为我在服务的 UI 线程中运行的 while
循环中。
所以我的问题是如何告诉 WCF 在 UI 线程以外的线程上运行我的服务操作,这样我就可以在那个其他线程中执行我的 while
循环?
最佳答案
您需要在服务的 [ServiceBehavior]
属性中使用 UseSynchronizationContext = false
选项。这将告诉 WCF 不要强制将所有请求发布到创建它的线程(在您的例子中是 UI 线程)。该属性将进入服务类(而不是接口(interface))。
关于c# - 在与服务线程不同的线程上运行服务操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7856311/