Cre*_*ive 2 c# multithreading locking
有两个流,第一个显示进程表,第二个流则考虑计数和显示.最初是为第一个推出,然后是第二个:
Thread t1 = new Thread(tmh1.FillTable);
Thread t2 = new Thread(tmh1.GetGeneralInfo);
t1.Start();
t2.Start();
Run Code Online (Sandbox Code Playgroud)
以下是在线程中运行的方法:
public void FillTable()
{
while (true)
{
lock (lockObj)
{
arr.Clear();
arr.AddRange(Process.GetProcesses());
TableFormatter.Line();
TableFormatter.Row("Name", "ID", "threads quantity", "Start time");
TableFormatter.Line();
}
Thread.Sleep(interval);
}
}
public void GetGeneralInfo()
{
while (true)
{
lock (lockObj)
{
Console.WriteLine(arr.Count.ToString());
}
Thread.Sleep(interval);
}
}
Run Code Online (Sandbox Code Playgroud)
结果:
0
-----------------------------------------------------------------------------
| Name | ID | threads quantity| Start time |
-----------------------------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)
但应该如下:
-----------------------------------------------------------------------------
| Name | ID | threads quantity| Start time |
-----------------------------------------------------------------------------
**68**
Run Code Online (Sandbox Code Playgroud)
如何使胎面以正确的顺序运行?
线程应该并行运行.如果你想在第一个线程完成时执行第二个线程执行的任务,只需让第一个线程执行第二个任务.
您还可以使用任务并行库的方法一个接一个地运行任务.
Task.Factory.StartNew(() => tmh1.FillTable()).ContinueWith(() => tmh1.GetGeneralInfo(), TaskScheduler.FromCurrentSynchronizationContext());
Run Code Online (Sandbox Code Playgroud)