简体   繁体   English

异步实现同步WCF操作

[英]Async implementation of synchronous WCF operation

I have .net 4.5 WCF service. 我有.net 4.5 WCF服务。 I will rewrite the service implementation to use EF6 to access DB. 我将重写服务实现以使用EF6访问数据库。 This service has many clients and handle many calls. 此服务有许多客户端并处理许多呼叫。 I cannot change service contract and clients. 我不能改变服务合同和客户。 Does it make sense to use Async EF operations like SaveAsync, at the end my service must return T not Task (becouse of the old clients). 使用像SaveAsync这样的异步EF操作是否有意义,最后我的服务必须返回T not Task(因为旧客户端)。

Update 更新

Exaple operation contract Exaple运营合同

[OperationContract]
public object AddEntity(object entity)
{
    using(var context = new MyContext())
    {
        context.Add(entity)
        var task = context.SaveChangesAsync()

        return task.Result;
    }
}

So even I am usining async the thread will be block by task.Result. 因此,即使我正在使用异步,线程将被task.Result阻塞。 I cannot use await becouse than the operation contract must be changed to return Task. 我不能使用等待因为操作合同必须更改为返回任务。 How to implement such scenario? 如何实现这样的场景?

Does it make sense to use Async EF operations like SaveAsync, at the end my service must return T not Task (becouse of the old clients). 使用像SaveAsync这样的异步EF操作是否有意义,最后我的服务必须返回T not Task(因为旧客户端)。

Yes, it does make sense and will boost scalability of your WCF service. 是的,它确实有意义,并将提高您的WCF服务的可扩展性。 You don't have to change the contracts to take advantage of async APIs on the server side. 您不必更改合同以利用服务器端的异步API。 The conversion can be totally transparent to the client, check this: 转换对客户端完全透明,请检查:

Different forms of the WCF service contract interface 不同形式的WCF服务合同接口

[OperationContract]
public async Task<object> AddEntityAsync(object entity)
{
    using(var context = new MyContext())
    {
        context.Add(entity)
        return await context.SaveChangesAsync();
    }
}

WCF should detect the async method and will route calls properly with no modification required on client side. WCF应检测异步方法并正确路由调用,而无需在客户端进行修改。

I guess that SaveChangesAsync returns a Task and not a Task<object> but you know what to do ;) 我想SaveChangesAsync返回一个Task而不是一个Task<object>但是你知道该怎么做;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM