class Program
{
static void AddNumber1(ref int num)
{
num++;
}
static void AddNumber2(ref int num)
{
num++;
}
static void Main(string[] args)
{
//var mre = new ManualResetEvent(false);
int num = 0;
var th1 = new Thread(() =>
{
for (int i = 1; i <= 10; i++)
{
AddNumber1(ref num);
}
});
var th2 = new Thread(() =>
{
for (int i = 1; i <= 10; i++)
{
AddNumber1(ref num);
}
});
th1.Start();
th2.Start();
Console.WriteLine(num);
Console.Write("Press any key to end :");
Console.ReadKey(true);
}
Asked
Active
Viewed 45 times
-1

Joseph Sible-Reinstate Monica
- 45,431
- 5
- 48
- 98

suyangzuo
- 75
- 2
- 8
-
1`Thread.Join` - https://stackoverflow.com/questions/2281926/c-sharp-waiting-for-multiple-threads-to-finish – mjwills Apr 20 '20 at 01:59
1 Answers
0
You also could use Tasks instead of Threads like
var th1 = Task.Run(() =>
{
for (int i = 1; i <= 10; i++)
{
AddNumber1(ref num);
}
});
var th2 = Task.Run(() =>
{
for (int i = 1; i <= 10; i++)
{
AddNumber1(ref num);
}
});
Task.WaitAll(th1, th2);
Console.WriteLine(num);

Roman Kalinchuk
- 718
- 3
- 14
-
also, Task.WhenAll(th1, th2) could be used to return task which will be completed when all of the tasks are completed – Roman Kalinchuk Apr 20 '20 at 02:13
-
-
Well, I have a question. Will the two tasks use 'num' in a same time just like thread? – suyangzuo Apr 20 '20 at 05:17
-
@suyangzuo they are running in parallel. Task is awrapper above Thread – Roman Kalinchuk Apr 20 '20 at 18:56