简体   繁体   English

C#中的线程处理

[英]Thread manipulation in C#

Hello I recently started learning c# in Visual Studio.. 您好,我最近开始在Visual Studio中学习c#。

I am trying to make a background process for my app. 我正在尝试为我的应用进行后台处理。

I created a process and started it but I can't pause it without breaking my application. 我创建了一个进程并启动了它,但是我不能在不中断应用程序的情况下暂停它。

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!";
        }
    }

Also thread.ThreadState always returns "Unstarted"... I tried using "ManualResetEvent" but this just freezes my app... Help? 另外thread.ThreadState总是返回“未启动” ...我尝试使用“ ManualResetEvent”,但这只会冻结我的应用程序。 :S :S

That's correct, you check ThreadState before calling Start() , thus it's unstarted. 没错,您在调用Start()之前检查ThreadState ,因此它没有启动。

As an unrelated note, you don't need that InvokeRequired check, it's always required in this context. 无关紧要的是,您不需要InvokeRequired检查,在这种情况下始终是必需的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM