Reputation: 1136
I am using CallContext.LogicalGetData in order to share information across asynchronous code.
I want to perform this kind of call in a 'thread-safe' fashion:
var val = CallContext.LogicalGetData(key);
if(val==null)
{
CallContext.LogicalSetData(key, initialValue);
}
return val;
Any idea on how to do that ?
Upvotes: 1
Views: 1149
Reputation: 26281
Use a lock:
private static readonly object _lock = new object();
public static object GetData(string key, object initialValue)
{
lock(_lock)
{
object val = CallContext.LogicalGetData(key);
if (val == null)
CallContext.LogicalSetData(key, initialValue);
return val;
}
}
Note: The class or method do not have to be static. Just make sure that all the threads use the same lock when accesing the critical section.
Upvotes: 1