📄 frmmorethreads.cs
字号:
using System;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;
using System.Collections.Generic;
namespace CodeForChapter11cs
{
public partial class frmMoreThreads : Form
{
public frmMoreThreads()
{
InitializeComponent();
}
long someCounter = 0;
private void button1_Click(object sender, EventArgs e)
{
someCounter = 0;
Thread t1 = new Thread(this.ThreadBoth); // this.ThreadFirst1);
t1.Name = "Worker Thread 1 ";
Thread t2 = new Thread(this.ThreadBoth); // this.ThreadSecond2);
t2.Name = "Worker Thread 2 ";
t1.Start();
t2.Start();
t1.Join();
t2.Join();
MessageBox.Show("Final result = " + someCounter.ToString());
}
#region race condition 1
private void ThreadFirst1()
{
for (long j = 0; j < 100000000; j++)
{
Debug.WriteLine(Thread.CurrentThread.Name + "before inc");
someCounter += 1;
}
MessageBox.Show(Thread.CurrentThread.Name, "Done");
}
private void ThreadSecond2()
{
for (long j = 0; j < 100000000; j++)
{
Debug.WriteLine(Thread.CurrentThread.Name + "before inc");
someCounter -= 1;
}
MessageBox.Show(Thread.CurrentThread.Name, "Done");
}
#endregion
private void ThreadBoth()
{
Debug.WriteLine(Thread.CurrentThread.Name + "enters method");
int localVar = 0;
localVar += 1;
//lock (someLock) // uncomment the lock region to achieve the undesired effects
//{
if (someCounter == 0)
{
Debug.WriteLine(Thread.CurrentThread.Name + "in if block");
Thread.Sleep(1); //simulate some longer activity
someCounter += localVar;
Debug.WriteLine(Thread.CurrentThread.Name + "just incremented");
}
else
{
Debug.WriteLine(Thread.CurrentThread.Name + "in else block");
someCounter += 3;
}
//} // end lock
return;
}
#region Not used in sample. Shows Monitor code
object someLock = new object();
private void SomeMethod()
{
// some code
Monitor.Enter(this);
try
{
// critical region, only 1 thread at a time enters this
}
finally
{
Monitor.Exit(this);
}
// other code
}
#endregion
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -