【问题标题】:C# how do I disable a button thats running on the main thread?C#如何禁用在主线程上运行的按钮?
【发布时间】:2016-09-03 12:12:07
【问题描述】:

我到处寻找答案,我认为这很容易找到,但显然不是。我听说过调用,但我不知道如何使用它或它是什么。 这是我的代码:

    public void Thread1(object sender, EventArgs e)
    {
        this.button1.Enabled = false;
        this.textBox2.Clear();
        this.textBox3.Clear();
        this.textBox4.Clear();
        this.textBox6.Text = "£" + "0";
        //Generate 3 random numbers

        Stopwatch timer = new Stopwatch();
        timer.Start();
        this.Refresh();
        //This is only part of this function
    }

    private void button1_Click(object sender, EventArgs e)
    {
        ThreadStart threadStart = new ThreadStart(() => Thread1(sender, e));
        Thread newThread = new Thread(threadStart);
        newThread.Start();
    }

【问题讨论】:

  • SafeInvoke 是线索。永远不要尝试从线程更新 UI 组件。在 MSDN 中查找。
  • 你为什么要在另一个线程中进行更新?

标签: c# multithreading invoke


【解决方案1】:

在后台线程中,在WinForms组件上使用Invoke()在UI线程上执行代码:

this.Invoke( () => {
    this.button1.Enabled = true;
    this.textBox2.Text = "whatever";
} );

文档:https://msdn.microsoft.com/en-us/library/a1hetckb.aspx

【讨论】:

  • 感谢工作:) 但是我需要编辑它。现在是这个; 'this.Invoke(new Action () => { this.button1.Enabled = true; this.textBox2.Text = "whatever"; } );'
猜你喜欢
  • 2019-11-18
  • 1970-01-01
  • 2015-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-02
  • 2016-12-19
  • 1970-01-01
相关资源
最近更新 更多