通常,OnDoSomethingCompleted() 将在 UI 线程上执行,即在幕后,某些东西正在调用一些(从概念上)看起来有点像这样的代码:
Dispatcher.BeginInvoke(() => OnDoSomethingCompleted());
这意味着 OnDoSomethingCompleted() 在 UI 线程决定合作并运行它之前不会被执行。大多数时候这很好,但有时您可能希望它运行得更快。基本方法是使用线程池进行原始调用,这意味着响应将从同一个线程池处理(不一定在同一个线程上)。如果您可以在此返回方法中进行一些真正的处理,并且不只是自动将其编组回 UI 线程,这可以在一定程度上加快您的处理速度。
Tomek(来自 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();
}
}
}