如何正确使用Interlocked.Add()?

时间:2018-03-21 20:25:19

标签: c# multithreading

来自文档here:"此类的方法有助于防止在线程更新可由其他线程访问的变量时调度程序切换上下文时可能发生的错误... "

此外,this question状态的答案"互锁方法可以同时保护任何数量的CORE或CPU"这看起来很清楚。

基于上面我认为Interlocked.Add()足以让多个线程对变量进行添加。显然我错了或者我使用的方法不正确。在下面的runnable代码中,我希望当Run()完成时,Downloader.ActiveRequestCount为零。如果我没有锁定对Interlocked.Add的调用,我会得到一个随机的非零结果。 Interlocked.Add()的正确用法是什么?

class Program
{
    private Downloader downloader { get; set; }

    static void Main(string[] args)
    {
        new Program().Run().Wait();
    }


    public async Task Run()
    {
        downloader = new Downloader();
        List<Task> tasks = new List<Task>(100);

        for (int i = 0; i < 100; i++)
            tasks.Add(Task.Run(Download));

        await Task.WhenAll(tasks);

        Console.Clear();
        //expected:0, actual when lock is not used:random number i.e. 51,115
        Console.WriteLine($"ActiveRequestCount is : {downloader.ActiveRequestCount}"); 
        Console.ReadLine();


    }

    private async Task Download()
    {
        for (int i = 0; i < 100; i++)
            await downloader.Download();
    }
}

public class Downloader :INotifyPropertyChanged
{
    private object locker = new object();
    private int _ActiveRequestCount;
    public int ActiveRequestCount { get => _ActiveRequestCount; private set => _ActiveRequestCount = value; }

    public async Task<string> Download()
    {
        string result = string.Empty;

        try
        {
            IncrementActiveRequestCount(1);
            result = await Task.FromResult("boo");
        }
        catch (Exception ex)
        {
            Console.WriteLine("oops");
        }
        finally
        {
            IncrementActiveRequestCount(-1);
        }

        return result;
    }


    public void IncrementActiveRequestCount(int value)
    {
        //lock (locker)       // is this redundant
        //{
            _ActiveRequestCount = Interlocked.Add(ref _ActiveRequestCount, value);
        //}

        RaisePropertyChanged(nameof(ActiveRequestCount));
    }

    #region INotifyPropertyChanged implementation
    public event PropertyChangedEventHandler PropertyChanged;
    public void RaisePropertyChanged([CallerMemberNameAttribute] string propertyName = "") => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    #endregion
}

1 个答案:

答案 0 :(得分:3)

替换

_ActiveRequestCount = Interlocked.Add(ref _ActiveRequestCount, value);

Interlocked.Add(ref _ActiveRequestCount, value);

Interlocked.Add是线程安全的,并且接受ref参数,以便它可以安全地进行分配。您另外执行(不必要的)不安全的分配(=)。只需删除它。