Skip to main content
 首页 » 编程设计

c#之静态变量和多线程

2024年02月13日11webabcd

C#.NET 程序中的所有线程都可以更新一个静态变量作为计数器是否是一个好习惯?
示例代码:

public class SomeTask  
{ 
static int count = 0; 
public void Process() 
{ 
 
    while(true) 
    { 
        //some repeated task 
        count++; 
        if(count>100000) 
        { 
            count=0; 
            break; 
        } 
    } 
} 
} 
 
public class WorkerRole : RoleEntryPoint 
{ 
   public override void Run() 
    { 
    while(true) 
    { 
 
        for (int i = 0; i < maxTasks; i++) 
        { 
            this.Tasks[i] = Task.Factory.StartNew(() => (new SomeTask()).Process()); 
        } 
        Task.WaitAll(this.Tasks); 
 
        //every 100000 in counter needs some updates at program level 
    } 
} 
} 

请您参考如下方法:

如果你无法避免,那也没关系。最好用Interlocked class增加计数器:

if (Interlocked.Increment(ref counter) % 100000 == 0) { 
    // Do something every hundred thousand times 
    // Use "== 1" if you also want to do it on the first iteration 
} 

当你只需要知道最后的计数时,我会留下下面的代码

在您的情况下,您可以将 count 保留为实例字段(即非静态),添加公共(public) getter 并在所有任务完成后对所有计数器求和:

public class SomeTask  
{ 
    int count = 0; 
    public int Count { get { return count; } } 
 
    public void Process() 
    { 
 
        while(true) 
        { 
            //some repeated task 
            count++; 
 
            if (something) 
                break; 
        } 
    }         
} 
 
var someTasks = new List<SomeTask>(); 
for (int i = 0; i < maxTasks; i++) 
{ 
    var someTask = new SomeTask(); 
    someTasks.Add(someTask); 
    this.Tasks[i] = Task.Factory.StartNew(() => someTask.Process()); 
} 
Task.WaitAll(this.Tasks); 
 
// Your total count 
var total = someTasks.Sum(t => t.Counter);