is there any way to increment a value of an int inside a task? or is this a correct syntax in incrementing an int in task? sample code:
public int erCount = 9;
static void Main(string[] args){
Task.Factory.StartNew(() => {
...do some task
if(errorfound)
erCount++;
});
Task.Wait();
Console.Writeline(erCount.toString());
}
I seem not to get it in incrementing value inside a thread. Any help would be great!
Your code is fine as long as you're not modifying the erCount
in multiple threads. In which case you'd need a lock or Interlocked.Increment
.
Your problem is you're not waiting for the started Task
to complete.
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());
}
You may altogether remove the shared field and return the error count. That way you can avoid unnecessary synchronization.
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());
}
You could use 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());
}
The reason its not incrementing is:
Console.Writeline(erCount.toString());
executes before the error count has been incremented.
Move that inside the task at the end, and it should work.
You probably need to have a read up on the Task parrallel library and how multithreading works.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.