开发者

thread safety question

I know we nee开发者_如何学运维d to take care of thread safety for static member variables inside the class. Do we need to worry about the instance member variables?


It depends on whether you want your type to be thread-safe... and what you mean by that.

Most of the time I think it's entirely reasonable to document that the type isn't thread-safe, but can be used safely from different threads with appropriate synchronization. Most .NET types fall into this category.

That would you can usually make sure that only "coordinating" objects need to worry about synchronization, rather than putting a lock in every method and property - a strategy which is painful, and doesn't really address the wider synchronization issues you're likely to run into anyway.

Of course, types which will naturally be used from multiple threads - ones specifically design to enable concurrency, or service locators etc, should be thread-safe - and be documented so. Likewise fully immutable types are naturally thread-safe to start with.

Finally, there's the matter of what counts as "thread-safe" to start with. You should read Eric Lippert's blog post on the matter to clarify what sort of thing you should be thinking about and documenting.


Yes you should care because the same class instance method could be passed as callback to multiple threads. Example:

var instance = new Foo();
ThreadPool.QueueUserWorkItem(instance.SomeInstanceMethod);
ThreadPool.QueueUserWorkItem(instance.SomeInstanceMethod);

The instance method now needs to be synchronized because in this case the shared state is the instance itself.


Consider the following code:

public void Execute()
{
    Task.Factory.StartNew(Iterrate);
    Task.Factory.StartNew(Add);
}

private List<int> _list = Enumerable.Range(1, 10).ToList();

private void Iterrate()
{
    foreach (var item in _list)
    {
        Console.WriteLine(item);
    }
}

private void Add()
{
    _list.Add(_list.Count);
}

This code will result (most of the times):

InvalidOperationException: Collection was modified; enumeration operation may not execute.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜