我想为我的家庭作业展示一个针对特定问题的信号量应用示例。我在我的 C# 表单中添加了 3 个按钮,我想表明在特定时间只有一个按钮在我的代码中执行银行帐户功能。当我在两秒钟内点击三个按钮时,银行账户功能必须只运行一次。因为我在银行帐户功能中有一个 Thread.Sleep(6000) 等待 6 秒。但是我的三个点击以 6 秒的间隔连续运行。连续按三个按钮时,如何将代码更改为仅运行一次。该代码是:
命名空间 semafor_form
{
public partial class Form1 : Form
{
Semaphore semafor=new Semaphore(1,1);
delegate void SetTextCallback(string text);
private void SetText(string text)
{
if (this.textBox2.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.textBox2.Text = text;
}
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void BankAccount()
{
semafor.WaitOne();
double a = Convert.ToDouble (textBox1.Text) + Convert.ToDouble (textBox2.Text);
Thread.Sleep(6000);
semafor.Release();
SetText(a.ToString());
}
private void btnATM_Click(object sender, EventArgs e)
{
Thread t = new Thread(new ThreadStart(BankAccount));
t.Start();
}
private void btnCOUNTER_Click(object sender, EventArgs e)
{
Thread t = new Thread(new ThreadStart(BankAccount));
t.Start();
}
private void btnINT_Click(object sender, EventArgs e)
{
Thread t = new Thread(new ThreadStart(BankAccount));
t.Start();
}
}
}