首页 > 解决方案 > 缓存 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);
    }
  }

标签: asp.netwcfcaching

解决方案


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);
    }
}

推荐阅读