gpt4 book ai didi

c# - 静态变量和多线程

转载 作者:太空宇宙 更新时间:2023-11-03 21:38:24 25 4
gpt4 key购买 nike

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);

关于c# - 静态变量和多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20630455/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com