Caching in windows forms application

Кэширование в приложениях платформы .NET Framework Caching in .NET Framework Applications

Кэширование позволяет хранить данные в памяти для быстрого доступа. Caching enables you to store data in memory for rapid access. При повторном доступе к данным приложения могут получать их из кэша вместо извлечения из исходного источника. When the data is accessed again, applications can get the data from the cache instead of retrieving it from the original source. Это может повысить производительность и масштабируемость. This can improve performance and scalability. Кроме того, кэширование обеспечивает доступность данных при временной недоступности источника данных. In addition, caching makes data available when the data source is temporarily unavailable.

Платформа .NET Framework предоставляет возможность кэширования, которую можно использовать для улучшения производительности и масштабируемости как серверных, так и клиентских приложений Windows, включая ASP.NET. The .NET Framework provides caching functionality that you can use to improve the performance and scalability of both Windows client and server applications, including ASP.NET.

В .NET Framework 3,5 и более ранних версиях ASP.NET предоставил реализацию кэша в памяти в System.Web.Caching пространстве имен. In the .NET Framework 3.5 and earlier versions, ASP.NET provided an in-memory cache implementation in the System.Web.Caching namespace. В предыдущих версиях .NET Framework кэширование было доступно только в System.Web пространстве имен и, следовательно, требовало зависимости от классов ASP.NET. In previous versions of the .NET Framework, caching was available only in the System.Web namespace and therefore required a dependency on ASP.NET classes. В платформе .NET Framework 4 пространство имен System.Runtime.Caching содержит интерфейсы API, предназначенные как для веб-приложений, так и для приложений, не связанных с Интернетом. In the .NET Framework 4, the System.Runtime.Caching namespace contains APIs that are designed for both Web and non-Web applications.

Кэширование данных Caching Data

Информацию можно кэшировать с помощью классов в пространстве имен System.Runtime.Caching. You can cache information by using classes in the System.Runtime.Caching namespace. Классы кэширования в нем предоставляют перечисленные ниже возможности. The caching classes in this namespace provide the following features:

Абстрактные типы, которые образуют основу для создания пользовательских реализаций кэша. Abstract types that provide the foundation for creating custom cache implementations.

Конкретная реализация кэша объектов в памяти. A concrete in-memory object cache implementation.

Абстрактный базовый класс кэширования (ObjectCache) определяет следующие задачи кэширования: The abstract base caching class (ObjectCache) defines the following caching tasks:

создание записей кэша и управление ими; Creating and managing cache entries.

указание сведений об окончании срока действия и вытеснении; Specifying expiration and eviction information.

активация событий, создаваемых в ответ на изменение записей кэша. Triggering events that are raised in response to changes in cache entries.

Класс MemoryCache является реализацией в памяти кэша объектов, представленного классом ObjectCache. The MemoryCache class is an in-memory object cache implementation of the ObjectCache class. Класс MemoryCache можно использовать для большинства задач кэширования. You can use the MemoryCache class for most caching tasks.

Класс MemoryCache моделируется на основе объекта кэша ASP.NET, определенного в пространстве имен System.Web.Caching. The MemoryCache class is modeled on the ASP.NET cache object that is defined in the System.Web.Caching namespace. Следовательно, внутренняя логика кэширования подобна логике, предоставляемой в более ранних версиях ASP.NET. Therefore, the internal caching logic similar to the logic that was provided in earlier versions of ASP.NET.

Пример использования кэширования в приложении WPF см. в разделе Пошаговое руководство. Кэширование данных приложения WPF. For an example of how to use to caching in a WPF application, see Walkthrough: Caching Application Data in a WPF Application.

Читайте также:  Устанавливаем операционную систему mac os

Кэширование в приложениях ASP.NET Caching in ASP.NET Applications

Классы кэширования в пространстве имен System.Runtime.Caching предоставляют функциональные возможности кэширования данных в ASP.NET. The caching classes in the System.Runtime.Caching namespace provide functionality for caching data in ASP.NET.

Если приложение предназначено для .NET Framework 3,5 или более ранней версии, необходимо использовать классы кэширования, определенные в System.Web.Caching пространстве имен. If your application targets the .NET Framework 3.5 or earlier, you must use the caching classes that are defined in the System.Web.Caching namespace. Дополнительные сведения см. в разделе Общие сведения о кэшировании в ASP.NET. For more information, see ASP.NET Caching Overview.

При разработке новых приложений рекомендуется использовать класс MemoryCache. When you develop new applications, we recommend that you use the MemoryCache class. Интерфейс API, предоставленный в пространстве имен System.Runtime.Caching, подобен API, предоставленному в пространстве имен Cache. The API that is provided in the System.Runtime.Caching namespace is like the API that is provided in the Cache namespace. Следовательно, этот API будет знаком вам, если вы использовали кэширование в более ранних версиях ASP.NET. Therefore, the API will be familiar if you used caching in earlier versions of ASP.NET. Пример использования кэширования в приложениях ASP.NET см. в разделе Пошаговое руководство. Кэширование данных приложения в ASP.NET. For an example of how to use caching in ASP.NET applications, see Walkthrough: Caching Application Data in ASP.NET.

Кэширование выходных данных Output Caching

Для ручного кэширования данных приложения можно использовать класс MemoryCache в ASP.NET. To manually cache application data, you can use the MemoryCache class in ASP.NET. ASP.NET также поддерживает кэширование выходных данных, при котором в памяти сохраняются созданные выходные данные страниц, элементов управления и HTTP-ответов. ASP.NET also supports output caching, which stores the generated output of pages, controls, and HTTP responses in memory. Кэширование выходных данных можно настроить декларативно на веб-странице ASP.NET или с помощью параметров в файле Web.config. You can configure output caching declaratively in an ASP.NET Web page or by using settings in the Web.config file. Дополнительные сведения см. в разделе Элемент outputCache для элемента caching (схема параметров ASP.NET). For more information, see outputCache Element for caching (ASP.NET Settings Schema).

ASP.NET позволяет расширить кэширование выходных данных путем создания пользовательских поставщиков кэша выходных данных. ASP.NET lets you extend output caching by creating custom output-cache providers. С помощью пользовательских поставщиков можно хранить кэшированное содержимое на других запоминающих устройствах, таких как диски, облачные хранилища и распределенные модули кэширования. By using custom providers, you can store cached content using other storage devices such as disks, cloud storage, and distributed cache engines. Для создания пользовательского поставщика кэша выходных данных необходимо создать класс, производный от класса OutputCacheProvider, и настроить для приложения использование пользовательского поставщика кэша выходных данных. To create a custom output cache provider, you create a class that derives from the OutputCacheProvider class and configure the application to use the custom output cache provider.

Кэширование в службах WCF REST Caching in WCF REST Services

Для служб WCF REST платформа .NET Framework позволяет использовать преимущества декларативного кэширования выходных данных, доступного в ASP.NET. For WCF REST services, the .NET Framework enables you to take advantage of the declarative output caching that is available in ASP.NET. Это дает возможность кэшировать ответы операций службы WCF REST. This enables you to cache responses from your WCF REST service operations. Когда пользователь отправляет запрос HTTP GET в службу, для которой настроено кэширование, ASP.NET отправляет обратно кэшированный ответ, а метод службы при этом не вызывается. When a user sends an HTTP GET request to a service that is configured for caching, ASP.NET sends back the cached response, and the service method is not called. По истечении срока действия кэша при следующей отправке пользователем запроса HTTP GET будет вызван метод службы, и ответ будет снова кэширован. After the cache expires, the next time that a user sends an HTTP GET request, your service method is called and the response is again cached.

Читайте также:  Windows desktop picture location

Платформа .NET Framework позволяет также реализовать условное кэширование HTTP GET. The .NET Framework also enables you to implement conditional HTTP GET caching. В сценариях REST условный HTTP-запрос GET часто используется службами для реализации интеллектуального HTTP-кэширования, которое описано в спецификации протокола HTTP. In REST scenarios, a conditional HTTP GET request is often used by services to implement intelligent HTTP caching as described in the HTTP Specification. Дополнительные сведения см. в разделе Поддержка кэширования для веб-служб HTTP WCF. For more information, see Caching Support for WCF Web HTTP Services.

Расширение кэширования в платформе .NET Framework Extending Caching in the .NET Framework

Кэширование в платформе .NET Framework предусматривает возможность расширения. Caching in the .NET Framework is designed to be extensible. Класс ObjectCache позволяет создавать пользовательскую реализацию кэша. The ObjectCache class enables you to create a custom cache implementation. Этот класс предоставляет члены, доступные всем управляемым приложениям, включая Windows Forms, Windows Presentation Foundation (WPF) и Windows Communications Foundation (WCF). This class provides members that are available to all managed applications, including Windows Forms, Windows Presentation Foundation (WPF), and Windows Communications Foundation (WCF). С помощью пользовательской реализации можно создать класс кэша, использующий другой механизм хранения, или обеспечить точный контроль над операциями кэша. You might do this in order to create a cache class that uses a different storage mechanism, or if you want granular control over cache operations.

Для расширения кэширования можно выполнить указанные ниже действия. To extend caching you can do the following:

Создайте пользовательский класс, производный от класса ObjectCache, а затем предоставьте в нем пользовательскую реализацию кэша. Create a custom class that derives from the ObjectCache class and then provide a custom cache implementation in the derived class.

Создайте класс, производный от класса MemoryCache, и настройте или расширьте его. Create a class that derives from MemoryCache class and customize or extend the derived class. Пример того, как это сделать, см. в записи блога Кэширование данных приложений с помощью нескольких объектов кэша в приложении ASP.NET. For an example of how to do this, see Caching Application Data by Using Multiple Cache Objects in an ASP.NET Application.

Создайте класс, производный от класса OutputCacheProvider, и настройте для приложения использование пользовательского поставщика кэша выходных данных. Create a class that derives from the OutputCacheProvider class and configure the application to use the custom output cache provider.

Caching in .NET Framework Applications

Caching enables you to store data in memory for rapid access. When the data is accessed again, applications can get the data from the cache instead of retrieving it from the original source. This can improve performance and scalability. In addition, caching makes data available when the data source is temporarily unavailable.

The .NET Framework provides caching functionality that you can use to improve the performance and scalability of both Windows client and server applications, including ASP.NET.

In the .NET Framework 3.5 and earlier versions, ASP.NET provided an in-memory cache implementation in the System.Web.Caching namespace. In previous versions of the .NET Framework, caching was available only in the System.Web namespace and therefore required a dependency on ASP.NET classes. In the .NET Framework 4, the System.Runtime.Caching namespace contains APIs that are designed for both Web and non-Web applications.

Caching Data

You can cache information by using classes in the System.Runtime.Caching namespace. The caching classes in this namespace provide the following features:

Abstract types that provide the foundation for creating custom cache implementations.

A concrete in-memory object cache implementation.

The abstract base caching class (ObjectCache) defines the following caching tasks:

Creating and managing cache entries.

Specifying expiration and eviction information.

Triggering events that are raised in response to changes in cache entries.

Читайте также:  Firefox linux firefox is already running

The MemoryCache class is an in-memory object cache implementation of the ObjectCache class. You can use the MemoryCache class for most caching tasks.

The MemoryCache class is modeled on the ASP.NET cache object that is defined in the System.Web.Caching namespace. Therefore, the internal caching logic similar to the logic that was provided in earlier versions of ASP.NET.

For an example of how to use to caching in a WPF application, see Walkthrough: Caching Application Data in a WPF Application.

Caching in ASP.NET Applications

The caching classes in the System.Runtime.Caching namespace provide functionality for caching data in ASP.NET.

If your application targets the .NET Framework 3.5 or earlier, you must use the caching classes that are defined in the System.Web.Caching namespace. For more information, see ASP.NET Caching Overview.

When you develop new applications, we recommend that you use the MemoryCache class. The API that is provided in the System.Runtime.Caching namespace is like the API that is provided in the Cache namespace. Therefore, the API will be familiar if you used caching in earlier versions of ASP.NET. For an example of how to use caching in ASP.NET applications, see Walkthrough: Caching Application Data in ASP.NET.

Output Caching

To manually cache application data, you can use the MemoryCache class in ASP.NET. ASP.NET also supports output caching, which stores the generated output of pages, controls, and HTTP responses in memory. You can configure output caching declaratively in an ASP.NET Web page or by using settings in the Web.config file. For more information, see outputCache Element for caching (ASP.NET Settings Schema).

ASP.NET lets you extend output caching by creating custom output-cache providers. By using custom providers, you can store cached content using other storage devices such as disks, cloud storage, and distributed cache engines. To create a custom output cache provider, you create a class that derives from the OutputCacheProvider class and configure the application to use the custom output cache provider.

Caching in WCF REST Services

For WCF REST services, the .NET Framework enables you to take advantage of the declarative output caching that is available in ASP.NET. This enables you to cache responses from your WCF REST service operations. When a user sends an HTTP GET request to a service that is configured for caching, ASP.NET sends back the cached response, and the service method is not called. After the cache expires, the next time that a user sends an HTTP GET request, your service method is called and the response is again cached.

The .NET Framework also enables you to implement conditional HTTP GET caching. In REST scenarios, a conditional HTTP GET request is often used by services to implement intelligent HTTP caching as described in the HTTP Specification. For more information, see Caching Support for WCF Web HTTP Services.

Extending Caching in the .NET Framework

Caching in the .NET Framework is designed to be extensible. The ObjectCache class enables you to create a custom cache implementation. This class provides members that are available to all managed applications, including Windows Forms, Windows Presentation Foundation (WPF), and Windows Communications Foundation (WCF). You might do this in order to create a cache class that uses a different storage mechanism, or if you want granular control over cache operations.

To extend caching you can do the following:

Create a custom class that derives from the ObjectCache class and then provide a custom cache implementation in the derived class.

Create a class that derives from MemoryCache class and customize or extend the derived class. For an example of how to do this, see Caching Application Data by Using Multiple Cache Objects in an ASP.NET Application.

Create a class that derives from the OutputCacheProvider class and configure the application to use the custom output cache provider.

Оцените статью