通常情况下,OnDoSomethingCompleted()将UI线程,即在被执行时,幕后的东西是调用一些代码(在概念上)看起来有点像这样:
Dispatcher.BeginInvoke(() => OnDoSomethingCompleted());
这意味着OnDoSomethingCompleted( )在UI线程决定合作并运行之前不会执行。大多数时间没问题,但有时候你希望它运行得更快。基本的方法是使用线程池进行原始调用,这意味着响应将从同一个线程池(不一定在同一个线程上)处理。如果你可以在这个返回方法中做一些真正的处理,并且不只是自动将它们编组回到UI线程,这可以加快你的处理速度。
托梅克(从MS WCF小组)给出了如何在这里做一个很好的例子:
http://tomasz.janczuk.org/2009/08/improving-performance-of-concurrent-wcf.html
这也是我的理解,对于WCF连接的同步情况下被设定,当你第一次打开它。这意味着无论第一次打开WCF连接的线程是处理所有稍后调用的线程。因此,在我自己的代码,我做这样的事情:
// Spin up the connection on a new worker thread.
// According to Tomek, this will cause all WCF calls to be made from this thread.
ManualResetEvent resetEvent = new ManualResetEvent(false);
wcfWorkerThread = new Thread(new ThreadStart(() => InitializeNotificationClient(resetEvent)));
wcfWorkerThread.Name = "WcfWorkerThread";
wcfWorkerThread.Start();
resetEvent.WaitOne();
然后InitializeNotificationClient()看起来是这样的:
private void InitializeNotificationClient(ManualResetEvent resetEvent = null)
{
try
{
notificationClient = GetRoomServiceClient();
notificationClient.OpenAsync(callback);
notificationClient.InnerChannel.Faulted += new EventHandler(Channel_Faulted);
notificationClient.InnerChannel.Closed += new EventHandler(Channel_Closed);
}
finally
{
// Tell the waiting thread that we're ready.
if (resetEvent != null)
{
resetEvent.Set();
}
}
}
是UI线程上执行的回调? – Gabe 2010-10-05 15:28:55
显示代码OnDoSomethingCompleted。 – AnthonyWJones 2010-10-05 16:20:10
DoSomethingAsync()在工作线程中调用。回调DoSomething()也在(不同的)工作线程中执行。 – Metro 2010-10-05 19:36:30