How can I wait for a thread to finish with .NET?

前端 未结 10 2309
有刺的猬
有刺的猬 2020-11-22 10:27

I\'ve never really used threading before in C# where I need to have two threads, as well as the main UI thread. Basically, I have the following.

public void S         


        
10条回答
  •  佛祖请我去吃肉
    2020-11-22 10:51

    Here's a simple example that waits for a tread to finish, within the same class. It also makes a call to another class in the same namespace. I included the "using" statements so it can execute as a Windows Forms form as long as you create button1.

    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.Threading;
    
    namespace ClassCrossCall
    {
    
        public partial class Form1 : Form
        {
            int number = 0; // This is an intentional problem, included
                            // for demonstration purposes
            public Form1()
            {
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                button1.Text = "Initialized";
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                button1.Text = "Clicked";
                button1.Refresh();
                Thread.Sleep(400);
                List taskList = new List();
                taskList.Add(Task.Factory.StartNew(() => update_thread(2000)));
                taskList.Add(Task.Factory.StartNew(() => update_thread(4000)));
                Task.WaitAll(taskList.ToArray());
                worker.update_button(this, number);
            }
    
            public void update_thread(int ms)
            {
                // It's important to check the scope of all variables
                number = ms; // This could be either 2000 or 4000. Race condition.
                Thread.Sleep(ms);
            }
        }
    
        class worker
        {
            public static void update_button(Form1 form, int number)
            {
                form.button1.Text = $"{number}";
            }
        }
    }
    

提交回复
热议问题