c# - 单独线程中的多个表单

标签 c# .net winforms multithreading

我正在尝试使用 Windows 窗体在 C# 中运行 ATM 模拟,它可以有多个 ATM 机实例同时与银行账户进行交易。

想法是使用信号量/锁定来阻止可能导致竞争条件的关键代码。

我的问题是:

如何在不同的线程上同时运行两个表单?特别是,所有这些如何与已经存在的 Application.Run() 相适应?

这是我的主要类(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;
    }
...

我试过用

Thread ATM2 = new Thread(new ThreadStart(/*What goes in here?*/));

但是我应该在 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();

在银行构造函数中。什么都不显示,程序在 Main() 函数结束时退出。

最佳答案

这是我认为你需要做的:

Thread ATM2 = new Thread(new ThreadStart(ThreadProc));
ATM2.Start();

它调用这个方法:

private void ThreadProc()
{
    var frm = new ATM();
    frm.ShowDialog();
}

关于c# - 单独线程中的多个表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9856596/

相关文章:

c# - 您是否会将此方法设为静态?

winforms - 路径递归是否应该发生在类或表示层中?

asp.net - WinForms 和 Asp 类库中的异常处理

c# - 无需安装即可使用 ClickOnce API

c# - 是否有可能在 DataGridView 中有一列用作允许用户输入新值的组合框?

c# - 为什么 null 条件运算符会更改常规属性访问?

c# - 用Deflate算法解压Span<byte>中的数据

.net - 使用 .net 连接表时无响应

c# - 如何检查我是否可以在特定文件夹中创建文件

c# - 动态 Linq select 语句