【问题标题】:How do I invoke a UI method from a Systems.Timers thread in C# [duplicate]如何从 C# 中的 Systems.Timers 线程调用 UI 方法 [重复]
【发布时间】:2015-03-24 15:41:59
【问题描述】:

我有一个 Windows 窗体应用程序。 我应该创建一个 SQL 作业并执行它。 SQL 作业由大约 9 个步骤组成,大约需要 4 小时才能完成。 我应该在 datagridview 中显示 SQL 作业的状态,这样就不必去 SQL 服务器和监视事件。

我的代码如下

 public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {


            Thread t1 = new Thread(FirstThread);
            t1.Start();
            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Interval = 500;
            timer.Enabled = true;

            timer.Elapsed += timer1_Tick;
            timer.Start();
            t1.Join();


        }
 private void FirstThread()
        {

            // Creates a job
            // Invoke the job, via a bat file

        }
 private void checkStatus()
        {            
            // Checks the status of the job using the EXEC sp_helpjob @jobName='JobName'
            // Populate the status on the DataGridView
            // If the status of the job, eg. 
            dataGridView1.DataSource = ds.Tables[0];
            int CurrentExecution = Convert.ToInt32(dt.Rows[0]["Current_Execution_Status"]);
            if (CurrentExecution == 4)
                label1.Text = "Job is Over";
        }

        private void timer1_Tick(object sender, EventArgs e)
        {

            checkStatus();
        }

我遇到了 CrossThread Operation Not valid 错误。谁能告诉我如何调用 System.Timer 线程中的 UI 控件。

【问题讨论】:

    标签: c# multithreading timer


    【解决方案1】:

    您应该在ControlForm 上致电Invoke

    this.Invoke((MethodInvoker)delegate() { label1.Text = "Job is Over"; });
    

    BeginInvoke,如果您不想等到操作结束:

    this.BeginInvoke((MethodInvoker)delegate() { label1.Text = "Job is Over"; });
    

    【讨论】:

    • 或致电BeginInvoke ;-)
    • @UweKeim:确实。已更新。
    • 或者使用SynchronizationContext或者更好的async-await;)
    • @SriramSakthivel:你是对的。有很多选择。有时太多:)
    • 但是即使datagridview显示Cross Thread操作错误,我如何在里面填充数据。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-24
    • 1970-01-01
    • 1970-01-01
    • 2012-12-15
    • 2012-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多