【问题标题】:Running own class on separate thread在单独的线程上运行自己的类
【发布时间】:2012-10-30 09:20:25
【问题描述】:

我想在另一个线程中运行自己的类,但如果这样做我不能使用我的标签,例如 EventHandler 中的标签,我该如何避免这种情况?

这就是我的代码的样子:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Ts3_Movearound
{
    public partial class Form1 : Form
    {
        TS3_Connector conn = new TS3_Connector();
        Thread workerThread = null;
        public Form1()
        {
            InitializeComponent();
            conn.runningHandle += new EventHandler(started);
            conn.stoppedHandle += new EventHandler(stopped);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //System.Threading.Thread connw = new System.Threading.Thread(conn);
            workerThread = new Thread(conn.Main);
            workerThread.Start();
        }

        public void started(Object sender, EventArgs e)
        {
            label1.Text = "Status: Running!";
        }
        public void stopped(Object sender, EventArgs e)
        {
            label1.Text = "Status: Stopped!";
        }
    }
}

这就是错误:

InvalidOperationExpetion in Line "label1.Text = "Status: Running!";"

【问题讨论】:

    标签: c#


    【解决方案1】:

    您只能通过 UI 线程更新控件。使用 label1.Invoke() 来做到这一点:

    label1.Invoke((MethodInvoker)delegate {
        label1.Text = "Status: Running!";"
    });
    

    【讨论】:

      【解决方案2】:

      我会考虑为此使用BackgroundWorker。然后,您可以使用以下内容:

      1) 在调用 RunWorkerAsync 之前,您将标签设置为运行,因为没有线程问题。 2)调用RunWorkerAsync后如果你设置任何控件使用:

                  label1.Invoke(new Action(() => label1.Text = @"Status: Running!"));
      

      3) 进程完成后,您可以通过将方法分配给 RunWorkerCompleted 事件来将标签设置为停止。这个方法应该没有线程问题,因为它在主线程上运行。

      【讨论】:

        【解决方案3】:
        猜你喜欢
        • 2016-05-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多