【发布时间】:2011-11-30 10:40:54
【问题描述】:
假设我们在 wcf 服务上定义了两个操作协定,同步和异步一个。有两个示例:
public void SubscribeSingle(int userId)
{
var clientId = this.OperationContext.GetClientId();
var session = this.OperationContext.GetPollingDuplexSession();
if (string.IsNullOrEmpty(clientId) || session == null || userId == 0)
{
return;
}
this.InternalSubscribeSingle(userId, clientId, session.SessionId);
}
和
public IAsyncResult BeginUnsubscribeSingle(int userId, AsyncCallback callback, object state)
{
var clientId = this.OperationContext.GetClientId();
var session = this.OperationContext.GetPollingDuplexSession();
if (string.IsNullOrEmpty(clientId) || session == null)
{
return null;
}
var asyncResult = new VoidAsyncResult(callback, state);
Task.Factory.StartNew(() =>
{
try
{
this.InternalUnsubscribeSingle(userId, clientId);
asyncResult.SetAsCompleted(false);
}
catch (Exception ex)
{
asyncResult.SetAsCompleted(ex, false);
}
});
return asyncResult;
}
public void EndUnsubscribeSingle(IAsyncResult result)
{
var response = result as VoidAsyncResult;
if (response != null)
{
response.EndInvoke();
}
}
据我了解,WCF 服务内部也有一个线程池,因此每个 I/O 操作都可能在另一个线程上完成。以及使用 Task.Factory.StartNew 启动新线程
如果数据库访问是通过 EntityFramework 并通过阻塞进行的,从性能的角度来看,同步服务器调用和异步服务器调用有什么区别?
【问题讨论】:
-
仅供参考 Stephen Toub 在本月的 MSDN 杂志上发表了一篇关于使用基于任务的异步模式的异步性能影响的文章。你可以在这里阅读:msdn.microsoft.com/en-us/magazine/hh456402.aspx
标签: c# .net wcf asynchronous task