Multiple forms in separate threads
I am trying to run ATM Simulator in C # using Windows Forms, which can have multiple ATM instances with a transaction at the same time with a bank account.
The idea is to use semaphores / locks to block critical code, which can lead to race conditions.
My question is:
How can I run two forms at the same time on separate threads? Specifically, how does it all fit into Application.Run()
one that already exists?
Here's my main class:
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;
}
...
I have tried using
Thread ATM2 = new Thread(new ThreadStart(/*What goes in here?*/));
But what method do I put in the ThreadStart constructor, since the ATM form is event driven and no one controls it?
EDIT:
I tried replacing Application.Run(new ATM(ac));
with
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();
in the constructor of the Bank. Nothing is displayed, and the program discards the end of the Main () function.
Here's what I think you need to do:
Thread ATM2 = new Thread(new ThreadStart(ThreadProc));
ATM2.Start();
It calls this method:
private void ThreadProc()
{
var frm = new ATM();
frm.ShowDialog();
}
The Bank.Main()
try to change Application.Run(new ATM(acc))
to new ATM(acc).Show()
. You can use the method Form.Show()
as many times as you like. If I remember correctly, the application will close when all forms are closed (although I may be wrong - try this with the VS debugger)
The above is unsafe code
Enter theme code:
Thread ATM2 = new Thread(new ThreadStart(ThreadProc));
ATM2.Start();
It calls this method:
private void ThreadProc()
{
if(InvokeRequired)
{
this.Invoke(new Action(() => CreateAndShowForm()));
return;
}
CreateAndShowForm();
}
private void CreateAndShowForm()
{
var frm = new ATM();
frm.ShowDialog();
}