Cal*_*ray 3 .net c# multithreading winforms
我正在尝试使用Windows窗体在C#中运行ATM模拟,该窗体可以有多个ATM机实例同时与银行账户进行交易.
我们的想法是使用信号量/锁定来阻止可能导致竞争条件的关键代码.
我的问题是:
如何在不同的线程上同时运行两个表单?特别是,所有这些如何适应Application.Run()
已经存在的东西?
这是我的主要课程:
public class Bank
{
private Account[] ac = new Account[3];
private ATM atm;
public Bank()
{
ac[0] = new Account(300, 1111, 111111);
ac[1] = new Account(750, 2222, 222222);
ac[2] = new Account(3000, 3333, 333333);
Application.Run(new ATM(ac));
}
static void Main(string[] args)
{
new Bank();
}
}
...that I want to run two of these forms on separate threads...
public partial class ATM : Form
{
//local reference to the array of accounts
private Account[] ac;
//this is a reference to the account that is being used
private Account activeAccount = null;
private static int stepCount = 0;
private string buffer = "";
// the ATM constructor takes an array of account objects as a reference
public ATM(Account[] ac)
{
InitializeComponent(); //Sets up Form ATM GUI in ATM.Designer.cs
this.ac = ac;
}
...
Run Code Online (Sandbox Code Playgroud)
我试过用了
Thread ATM2 = new Thread(new ThreadStart(/*What goes in here?*/));
Run Code Online (Sandbox Code Playgroud)
但是我在ThreadStart构造函数中放入了什么方法,因为ATM表单是事件驱动的,并且没有一种方法可以控制它?
编辑:
我试着更换Application.Run(new ATM(ac));
用
ATM atm1 = new ATM(ac);
ATM atm2 = new ATM(ac);
Thread ATM2_T = new Thread(new ThreadStart(atm1.Show));
Thread ATM1_T = new Thread(new ThreadStart(atm2.Show));
ATM1_T.Start();
ATM2_T.Start();
Run Code Online (Sandbox Code Playgroud)
在银行构造函数中.没有显示任何内容,程序会从Main()函数的末尾删除.
这是我认为你需要做的事情:
Thread ATM2 = new Thread(new ThreadStart(ThreadProc));
ATM2.Start();
Run Code Online (Sandbox Code Playgroud)
它调用这个方法:
private void ThreadProc()
{
var frm = new ATM();
frm.ShowDialog();
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10042 次 |
最近记录: |