asp.net - 缓存 WCF 服务并将数据转换为异步
问题描述
我们正在尝试缓存 WCF 服务的数据,因此当数据在缓存内存中可用时,我们需要从缓存中以 AsyncResult 的形式返回缓存的数据,因为数据是对象类型并且 Start 方法是 IAsyncResult。
在这里我不能更改返回类型,因为它是辅助类中的抽象成员。
以及我无法从可用的父页面缓存中检查并通过,因为这需要全局更改,以便使用此服务的人可以使用它。
public override IAsyncResult Start(object sender, EventArgs e, AsyncCallback cb, object extraData)
{
if(cache.Get("key")
{
//Needs to return the result Async format which is there as object in cache.
}
svc = new service.GetData(m_url);
if (m_debug_mode) // not thread safe
{
return ((service.GetData)svc).BeginCallDataDebug(request, cb, extraData);
}
return ((service.GetData)svc).BeginCallData(request, cb, extraData);
}
public override void End(IAsyncResult ar)
{
try
{
data = ((service.GetData)m_svc).EndCallData(ar);
if(data !=null)
cache.Add("key", data, null, absoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
}
catch(Exception ex)
{
Log(ex.message);
}
}
解决方案
System.Threading.Tasks.Task
实现IAsyncResult
。
如果在缓存中找到数据,您可以Task
通过Task.FromResult
. 否则,您将调用该服务。
public override IAsyncResult Start(object sender, EventArgs e, AsyncCallback cb, object extraData)
{
Object cachedData = cache.Get("key");
if (cachedData != null)
{
// Return cached data.
return Task.FromResult<object>(cachedData);
}
// Make call to the service.
svc = new service.GetData(m_url);
if (m_debug_mode) // not thread safe
{
return ((service.GetData)svc).BeginCallDataDebug(request, cb, extraData);
}
return ((service.GetData)svc).BeginCallData(request, cb, extraData);
}
在End
方法中,您可以检查IAsyncResult
类型以访问结果值。
(或者您在方法中设置一个状态标志/字段,Start
说明您是否调用了服务;您可以检查svc
使用缓存数据时将为空的服务字段。)
public override void End(IAsyncResult ar)
{
try
{
Task<object> task = ar as Task<object>;
if (task != null)
{
data = task.Result;
}
else
{
data = ((service.GetData)m_svc).EndCallData(ar);
if(data !=null)
cache.Add("key", data, null, absoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
}
}
}
catch(Exception ex)
{
Log(ex.message);
}
}
推荐阅读
- micronaut - micronaut 是否有能力连接到像 rabbitmq 一样支持“amqp/mqtt”协议的 artemis?
- java - 如何在 tomcat 容器中的 Spring Boot 多部分控制器操作中捕获 FileSizeLimitExceededException?
- c# - 如何按 ID 创建行组并在 datagridview 中分隔组?
- android - 如何制作不弹出的Android本地通知,只显示在通知列表中?
- android - 导航架构片段重载问题
- android - 使用 Rxjava2 的改造 2 发送 GET 请求,获取空对象
- r - 如何检测另一个字符串向量中的多个字符串
- php - curl_getinfo() 显示执行前后的空参数
- angular - *ngFor 在 Angular 6 中使用 jsPDF 时不显示数据
- python - Python比较两个特定的字典