C#中的线程操作

本文关键字:操作 线程 | 更新日期: 2023-09-27 18:20:56

你好,我最近开始在Visual Studio中学习c#。。

我正在尝试为我的应用程序创建一个后台进程。

我创建了一个进程并启动了它,但我无法在不中断应用程序的情况下暂停它。

public void WorkThreadFunction()
    {
    run = true;
        for (int i = 0; i < 100; i++)
        {
            string message = "'r'n"+i+" Running...";
            if (txtBox.InvokeRequired == true)
                txtBox.Invoke((MethodInvoker)delegate { txtBox.Text += message; });
            else
                txtBox.Text += message;
            Thread.Sleep(1000);
        }
    }
    private void btnCapture_Click(object sender, EventArgs e)
    {
        Thread thread = new Thread(WorkThreadFunction);
        if (run == false)
        {
            btnCapture.Text = "Abort";
            lblStatus.Text = "Thread status: " + thread.ThreadState;
            thread.Start();
        }
        else
        {
            btnCapture.Text = "Capture";
            lblStatus.Text = "Thread status: " + thread.ThreadState;
            //thread.Abort(); thread.Unset(); Thread.Sleep(999999); thread.WaitOne();
            txtBox.Text += "Work!";
        }
    }

还有螺纹。ThreadState总是返回"Unstarted"。。。我尝试使用"手动重置事件",但这只是冻结了我的应用程序。。。帮助?:S

C#中的线程操作

这是正确的,在调用Start()之前检查ThreadState,因此它是未启动的。

作为一个无关的注意事项,您不需要InvokeRequired检查,在这种情况下它总是必需的。