C# manual lock/unlock

前端 未结 5 2258
没有蜡笔的小新
没有蜡笔的小新 2020-12-01 08:25

I have a function in C# that can be called multiple times from multiple threads and I want it to be done only once so I thought about this:

class MyClass
{
          


        
5条回答
  •  北荒
    北荒 (楼主)
    2020-12-01 08:31

    I know this answer comes several years late, but none of the current answers seem to address your actual scenario, which only became apparent after your comment:

    The other threads don't need to use any information generated by ReallyDoSomething.

    If the other threads don't need to wait for the operation to complete, the second code snippet in your question would work fine. You can optimize it further by eliminating your lock entirely and using an atomic operation instead:

    private int done = 0;
    public void DoSomething()
    {
        if (Interlocked.Exchange(ref done, 1) == 0)   // only evaluates to true ONCE
            _DoSomething();
    }
    

    Furthermore, if your _DoSomething() is a fire-and-forget operation, then you might not even need the first thread to wait for it, allowing it to run asynchronously in a task on the thread pool:

    int done = 0;
    
    public void DoSomething()
    {
        if (Interlocked.Exchange(ref done, 1) == 0)
            Task.Factory.StartNew(_DoSomething);
    }
    

提交回复
热议问题