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.
Posted
Updated 28-Aug-21 3:13am
Comments
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.

https://www.google.com/search?q=c%23+parallel+methods&rlz=1C1CHWL_enTH966TH966&sxsrf=AOaemvJK3KQFSluuRN2W1zmtEV5D89oGoA%3A1630151698854&ei=EiQqYY_GM7PDpgfY8JmgDA&oq=c%23+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[^]
   
v2

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