【发布时间】:2011-12-23 19:26:58
【问题描述】:
我正在尝试使 WCF REST 方法完全异步(我不想在任何地方阻塞)。本质上,我有一个简单的 3 层服务:服务、业务逻辑和数据访问层。数据访问层正在访问数据库,可能需要几秒钟才能从该方法获得响应。
我不太了解如何链接所有这些方法。有人可以帮我完成我要在下面写的示例吗?我不太了解 WCF 使用的模式,也没有找到关于该主题的太多文档。
有人可以帮我完成以下示例吗?此外,我如何衡量服务将能够处理比典型同步实现更多的负载?
using System;
using System.Collections.Generic;
using System.Runtime.Remoting.Messaging;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Threading.Tasks;
namespace WcfRestService1
{
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode =
AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class Service1
{
private BusinessLogic bll = new BusinessLogic();
// Synchronous version
[WebGet(UriTemplate = "/sync")]
public string GetSamples()
{
return bll.ComputeData();
}
// Asynchronous version - Begin
[WebGet(UriTemplate = "/async")]
[OperationContract(AsyncPattern = true)]
public IAsyncResult BeginGetSampleAsync(AsyncCallback callback,
object state)
{
Task<string> t = bll.ComputeDataAsync();
// What am I suppose to return here
// return t.AsyncState; ???
}
// Asynchronous version - End
public List<SampleItem> EndGetSampleAsync(IAsyncResult result)
{
// How do I handle the callback here?
}
}
public class BusinessLogic
{
public Task<string> ComputeDataAsync()
{
DataAccessLayer dal = new DataAccessLayer();
return dal.GetData();
}
public string ComputeData()
{
Task<string> t = this.ComputeDataAsync();
// I am blocking... Waiting for the data
t.Wait();
return t.Result;
}
}
public class DataAccessLayer
{
public Task<string> GetData()
{
// Read data from disk or network or db
}
}
}
【问题讨论】:
-
您的部分答案在这里:stackoverflow.com/questions/5161159/…,但不确定 REST 部分
-
您是否希望您的数据库占用时间最长并且您打算使用 EF 吗?因为 EF 没有像 BeginExecuteReader 这样的异步方法,所以你可以启动一个任务,它会释放你的 wcf 线程,但是通过任务调用 EF 仍然会阻塞......
-
你能解释一下为什么吗?听起来您可能正在尝试使用错误的解决方案来解决问题。
-
@np-hard:我不打算使用 EF。我不是想让 WCF 服务“更快”,我希望它能够处理更多负载(即更多连接和更少线程)
-
请查看使用sql命令更新的代码,异步模式一直到数据层。
标签: c# wcf asynchronous task-parallel-library