线程化2种形式同时使用C#

时间:2016-11-06 15:13:23

标签: c# .net multithreading winforms

上下文:我有一个带有多个复选框“按钮”的表单 在mainform中我有一个do-while循环,需要检查form.checkBox.Checked实时更新一些变量。
我尝试在异步工作程序中运行循环,线程化form2,在form2中运行循环,都没有成功。

错误代码:

namespace CSharp
{
    public partial class MainForm : Form
    {
        bool exit_state = true;
        private BackgroundWorker worker = null;
        public MainForm()
        {
            InitializeComponent();
        }
        private void bRecord_Click(object sender, EventArgs e)
        {
            System.IO.StreamWriter file = new System.IO.StreamWriter(AppDomain.CurrentDomain.BaseDirectory + DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss") + ".xml", true);
            string behavior = null;
            exit_state = false;
            form2 form = new form2();
            form2.ShowDialog();
            worker = new BackgroundWorker();
            worker.WorkerSupportsCancellation = true;
            worker.DoWork += new DoWorkEventHandler((state, args) =>
            {
                do
                {
                    if (form2.checkBox1.Checked) behavior = form2.checkBox1.Text;
                    if (form2.checkBox2.Checked) behavior = form2.checkBox2.Text;
                    file.WriteLine(behavior);
                }
                while(exit_state==false);
            });
        }
        private void bStop_Click(object sender, EventArgs e)
        {
            exit_state = true;
            _worker.CancelAsync();
        }
    }
}

我相信这是使用每个表单的线程解决的,但我缺乏线程知识的知识。

编辑:我现在意识到我不够明确,并且提出了错误的问题所以我开始了new one

0 个答案:

没有答案