One of the features of the INamedCache
interface is the ability to add cache listeners that receive events emitted by a cache as its contents change. These events are sent from the server and dispatched to registered listeners by a background thread.
The .NET Single-Threaded Apartment model prohibits windows form controls created by one thread from being updated by another thread. If one or more controls should be updated as a result of an event notification, you must ensure that any event handling code that must run as a response to a cache event is executed on the UI thread. The WindowsFormsCacheListener
helper class allows end users to ignore this fact and to handle Coherence cache events (which are always raised by a background thread) as if they were raised by the UI thread. This class will ensure that the call is properly marshalled and executed on the UI thread.
Here is the sample of using this class:
Example 20-1 Marshalling and Executing a Call on the UI Thread
public partial class ContactInfoForm : Form { ... listener = new WindowsFormsCacheListener(this); listener.EntryInserted += new CacheEventHandler(AddRow); listener.EntryUpdated += new CacheEventHandler(UpdateRow); listener.EntryDeleted += new CacheEventHandler(DeleteRow); ... cache.AddCacheListener(listener); ... }
The AddRow
, UpdateRow
and DeleteRow
methods are called in response to a cache event:
Example 20-2 Calling Methods in Response to a Cache Event
private void AddRow(object sender, CacheEventArgs args) { ... } private void UpdateRow(object sender, CacheEventArgs args) { ... } private void DeleteRow(object sender, CacheEventArgs args) { ... }
The CacheEventArgs
parameter encapsulates the IObservableCache
instance that raised the cache event; the CacheEventType
that occurred; and the Key
, NewValue
and OldValue
of the cached entry.