缓存WCF服务并将数据转换为异步

时间:2019-05-03 12:13:18

标签: asp.net wcf caching

我们正在尝试缓存WCF服务的数据,因此,当缓存中有可用数据时,由于数据是对象类型并且Start方法是IAsyncResult,因此需要从缓存中以AsyncResult的形式返回缓存的数据。 / p>

在这里,我无法更改返回类型,因为它是助手类中的抽象成员。

我无法从父页面中检查可用缓存并通过,因为这需要全局更改,以便使用此服务的人可以使用它。

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

1 个答案:

答案 0 :(得分:1)

System.Threading.Tasks.Task实现IAsyncResult

如果在缓存中找到数据,则可以通过Task.FromResult返回一个完整的Task及其结果。否则,您将调用该服务。

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字段,当使用缓存数据时该字段将为null 。)

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