Thread in C# - Part 15: Local Storage  
 

(Post 27/11/2007) Each thread gets a data store isolated from all other threads. This is useful for storing "out-of-band" data – that which supports the execution path's infrastructure, such as messaging, transaction or security tokens. Passing such data around via method parameters would be extremely clumsy and would alienate all but your own methods; storing such information in static fields would mean sharing it between all threads.

Thread.GetData reads from a thread's isolated data store; Thread.SetData writes to it. Both methods require a LocalDataStoreSlot object to identify the slot – this is just a wrapper for a string that names the slot – the same one can be used across all threads and they'll still get separate values. Here's an example:

class ... {
// The same LocalDataStoreSlot object can be used across all threads.
LocalDataStoreSlot secSlot = Thread.GetNamedDataSlot ("securityLevel");

// This property has a separate value on each thread.
int SecurityLevel {
get {
object data = Thread.GetData (secSlot);
return data == null ? 0 : (int) data; // null == uninitialized
}
set {
Thread.SetData (secSlot, value);
}
}
...

Thread.FreeNamedDataSlot will release a given data slot across all threads – but only once all LocalDataStoreSlot objects of the same name have dropped out of scope and been garbage collected. This ensures threads don't get data slots pulled out from under their feet – as long as they keep a reference to the appropriate LocalDataStoreSlot object for as long as it's in use.

(Sưu tầm)


 
 

 
     
 
Công nghệ khác:


Thread in C# - Part 14: TimersThread in C# - Part 13: Asynchronous Delegates
Thread in C# - Part 12: Thread PoolingThread in C# - Part 11: ReaderWriterLock
Thread in C# - Part 10: BackgroundWorkerThread in C# - Part 9: Apartments and Windows Forms
  Xem tiếp    
 
Lịch khai giảng của hệ thống
 
Ngày
Giờ
T.Tâm
TP Hồ Chí Minh
Hà Nội
 
   
New ADSE - Nhấn vào để xem chi tiết
Mừng Sinh Nhật Lần Thứ 20 FPT-APTECH
Nhấn vào để xem chi tiết
Bảng Vàng Thành Tích Sinh Viên FPT APTECH - Nhấn vào để xem chi tiết
Cập nhật công nghệ miễn phí cho tất cả cựu sinh viên APTECH toàn quốc
Tiết Thực Vì Cộng Đồng
Hội Thảo CNTT
Những khoảnh khắc không phai của Thầy Trò FPT-APTECH Ngày 20-11