Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update an int variable from tasks?

I currently have a function that will create X tasks of a function based on the amount of data and I would like to update an int variable with how many data each thread have executed to show a progressBar.

Currently all my UI is updated from a timer so instead of delegating from the threads to update the UI (which I believe would be a lot more trouble in this case) I will update a variable with the count that will later be picked by the timer and update the UI.

What I would like to know is, would a lock be a good way to update the variable or is there a better way ?

Will the timer be able to read that variable if it is being used very frequently or it would still be able to read it even if an older value while its being updated ?

Here is a roughly example:

private static readonly object counterLock = new object();
int myCounter = 0;

private void FunctionExecutedByAllRunnningThreads()
{
    int executed = 0;
    foreach (some data)
    {
        //do something with this data
        executed++;
    }
    lock (counterLock)
        myCounter += executed;
}
like image 838
Guapo Avatar asked Jan 25 '26 20:01

Guapo


2 Answers

What I would like to know is, would a lock be a good way to update the variable or is there a better way?

If you're just incrementing the value, you could use Interlocked.Increment to safely increment it without a lock.

If you want to batch this, Interlocked.Add will let you add your thread-local total value to the counter in one shot, again without locking.

like image 53
Reed Copsey Avatar answered Jan 28 '26 12:01

Reed Copsey


Use Interlocked.Add() for this. (You can't use Interlocked.Increment() since you appear to be adding more than 1 to the counter)

like image 39
Matthew Watson Avatar answered Jan 28 '26 10:01

Matthew Watson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!