简体   繁体   中英

C# how do I disable a button thats running on the main thread?

I have looked everywhere for the answer and I thought it would be simple to find but apparently not. I've heard about invoke but I have no idea how to use it or what it is. Here is my code:

    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();
    }

In background threads, use Invoke() on WinForms components to execute code on the UI thread:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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