将缓存数据存储在本地

Leo*_* Vo 4 c# caching winforms

我开发了一个 C# Winform 应用程序,它是一个客户端并连接到 Web 服务以获取数据。webservice返回的数据是一个DataTable。客户端将其显示在 DataGridView 上。

我的问题是:客户端将花费更多时间从服务器获取所有数据(Web 服务不是客户端本地的)。所以我必须使用线程来获取数据。这是我的模型:

客户端创建一个线程来获取数据 -> 线程完成并将事件发送到客户端 -> 客户端在表单上的 datagridview 上显示数据。

但是,当用户关闭表单时,用户可以再次打开该表单,客户端必须重新获取数据。这种解决方案会导致客户端缓慢。

所以,我想到了一个缓存数据:

客户端<---获取/添加/编辑/删除--->缓存数据---获取/添加/编辑/删除--->服务器(Web服务)

请给我一些建议。示例:缓存数据应该在与客户端同一主机的另一个应用程序中开发吗?或者缓存的数据正在客户端运行。请给我一些实现此解决方案的技术。

如果有任何例子,请给我。

谢谢。

更新:大家好,也许到目前为止你认为我的问题。我只想在客户端的生命周期内缓存数据。我认为缓存数据应该存储在内存中。当客户端想要获取数据时,它会从缓存中检查。

Phi*_*ove 5

如果您使用的是 C# 2.0并且准备将 System.Web 作为依赖项提供,那么您可以使用 ASP.NET 缓存:

using System.Web;
using System.Web.Caching;

Cache webCache;

webCache = HttpContext.Current.Cache;

// See if there's a cached item already
cachedObject = webCache.Get("MyCacheItem");

if (cachedObject == null)
{
    // If there's nothing in the cache, call the web service to get a new item
    webServiceResult = new Object();

    // Cache the web service result for five minutes
    webCache.Add("MyCacheItem", webServiceResult, null, DateTime.Now.AddMinutes(5), Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null);
}
else
{
    // Item already in the cache - cast it to the right type
    webServiceResult = (object)cachedObject;
}
Run Code Online (Sandbox Code Playgroud)

如果您不准备发布 System.Web,那么您可能需要查看Enterprise Library Caching 块

但是,如果您使用的是 .NET 4.0,则缓存已被推送到 System.Runtime.Caching 命名空间中。要使用它,您需要添加对 System.Runtime.Caching 的引用,然后您的代码将如下所示:

using System.Runtime.Caching;

MemoryCache cache;
object cachedObject;
object webServiceResult;

cache = new MemoryCache("StackOverflow");

cachedObject = cache.Get("MyCacheItem");

if (cachedObject == null)
{
    // Call the web service
    webServiceResult = new Object();

    cache.Add("MyCacheItem", webServiceResult, DateTime.Now.AddMinutes(5));
}
else
{
    webServiceResult = (object)cachedObject;
}
Run Code Online (Sandbox Code Playgroud)

所有这些缓存都在客户端的进程内运行。正如 Adam 所说,因为您的数据来自 Web 服务,所以您将很难确定数据的新鲜度 - 您必须对数据更改的频率以及缓存数据的时间做出判断为了。