Click here to Skip to main content
15,063,085 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I just discovered threads because I needed to have two independent while loops.

In my main program, I want to be able to create and start a thread that is able to modify local variables in the main thread. If I define "int number = 1;" in main, can a thread started in the main program access and modify number ? I envision multiple threads containing a while loop that run continuously checking and updating various variables.

What I have tried:

So far I have

int number = 1;

I think I know how to create thread objects that call on methods.
Updated 28-Aug-21 3:13am
Richard MacCutchan 28-Aug-21 7:36am
Yes you can modify variables from multiple threads but you need to synchronise the threads, so that one does not overwrite the update of another.
Admin BTA 28-Aug-21 11:59am
Thanks, bro. Good one.
BillWoodruff 28-Aug-21 7:57am
This sounds to me like a scenario where you can use the parallel methods.

1 solution

The recommended way nowadays is to use Tasks, when a Task completes you can put the result in a local variable. See this CodeProject article to get an idea:
The Basics of Task Parallelism via C#[^]
And also this series of articles: Task Parallel Library: 1 of n[^]

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900