更新Task c#中的Int32
本文关键字:Int32 中的 Task 更新 | 更新日期: 2023-09-27 17:50:59
是否有任何方法可以在任务内增加int值?或者这是一个正确的语法在增加任务中的int ?示例代码:
public int erCount = 9;
static void Main(string[] args){
Task.Factory.StartNew(() => {
...do some task
if(errorfound)
erCount++;
});
Task.Wait();
Console.Writeline(erCount.toString());
}
我似乎没有得到它在一个线程内的增量值。任何帮助都太好了!
只要不在多个线程中修改erCount
,代码就没问题。在这种情况下,您需要一个锁或Interlocked.Increment
。
你的问题是你没有等待启动的Task
完成。
public static int erCount = 9;
static void Main(string[] args)
{
var task = Task.Factory.StartNew(() =>
{
...do some task
if(errorfound)
Interlocked.Increment(ref erCount);
});
task.Wait();//Wait for the task to complete
Console.Writeline(erCount.toString());
}
您可以完全删除共享字段并返回错误计数。这样可以避免不必要的同步。
public static int erCount = 9;
static void Main(string[] args)
{
var task = Task.Factory.StartNew(() =>
{
int localErrorCount =0;
...do some task
if(errorfound)
localErrorCount++;
return localErrorCount;
});
int errors = task.Result;//Wait for the task to complete and get the error count
erCount += errors;
Console.Writeline(erCount.toString());
}
您可以使用Interlocked.Increment():
public int erCount = 9;
static void Main(string[] args){
var task = Task.Factory.StartNew(() =>{
...do some task
if(errorfound)
Interlocked.Increment(ref erCount);
});
task.Wait(); // Wait for the task to complete before showing the error count
Console.Writeline(erCount.toString());
}
不递增的原因是:
Console.Writeline(erCount.toString());
在错误计数增加之前执行。
把它移到任务的最后,它应该可以工作。
您可能需要阅读Task并行库以及多线程如何工作。