An object may require to be accessed only by a predefined set of threads. Maybe these threads have some required information attached to their local storage (TLS), or maybe synchronized access to the object is ensured by limiting access to a single thread.
A synchronization context may be used to act as a proxy between the outside world's threads and the synchronized object. The synchronization context intercepts incoming calls, and redispatches them to one of the allowed threads.
This design pattern requires the synchronized object to publish it's synchronization context, and it's users to access the object through this context. Alternatively, the synchronized object could redirect all incoming calls to it's synchronization context by itself, thus encapsulating this requirement.
SyncObject syncObject = CreateSyncObject();
SynchronizationContext syncContext = syncObject.GetSynchronizationContext();
SendOrPostCallback methodCall = new SendOrPostCallback(syncObject.DoWork);
syncContext.Send(methodCall, someObjectParameter);
Synchronized objects then need to know which context they belong to. This context could be defined by the synchronized object itself when it is created, or if the object is known to be created from one of the synchronization context's threads, the object can get this information by calling SynchronizationContext.Current from it's constructor.
Saturday, August 16, 2008
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment