Skip to main content
 首页 » 编程设计

c#之异步多任务线程问题

2024年02月13日11rubylouvre

我正在尝试异步执行多个 (n) 任务,这些任务聚合为一个总和结果。目前我有以下内容:

public class Foo 
{ 
    public async void DoWork() 
    { 
        var stopwatch = Stopwatch.StartNew(); 
        List<Task> tasks = new List<Task>(); 
 
        var bar = new Bar(); 
 
        for (int i = 0; i < 20; i++) 
        { 
            var task = Task.Run(() => 
            { 
                Thread.Sleep(500); 
 
                bar.Count1++; 
                bar.Count2++; 
            }); 
 
            tasks.Add(task); 
        } 
 
        await Task.WhenAll(tasks.ToArray()); 
 
        Console.WriteLine("All done, Bar Count1: " + bar.Count1 + ", Count2: " + bar.Count2); 
        stopwatch.Stop(); 
        Console.WriteLine("Time taken " + stopwatch.ElapsedMilliseconds + " ms"); 
    } 
} 
 
public class Bar 
{ 
    public int Count1 { get; set; } 
    public int Count2 { get; set; } 
} 

我希望 bar.Count1 和 bar.Count2 在此处执行结束时的值为 20,但是,每次运行程序时我都会得到不同的值它们每个的值(大部分时间 < 20)。我该如何解决这个问题?

请您参考如下方法:

这里没有关闭问题。 ++ operator is not thread safe .所以你需要一把锁。

lock(bar) 
{     
    bar.Count1++; 
    bar.Count2++;     
} 

这应该可以解决问题。