[英]Update Int32 in Task c#
有什么办法可以增加任务中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
,您的代码就可以了。 在这种情况下,您需要使用lock或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并行库以及多线程的工作方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.