joe 发表于 2022-6-9 15:47:16

Task多线程

    public partial class Test : Form
    {
      static StringBuilder sb = new StringBuilder();
      static int step = -1;
      public Test()
      {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
      }

      private void button1_Click(object sender, EventArgs e)
      {
            step = -1;
            sb = new StringBuilder();
            string thread_id = Thread.CurrentThread.ManagedThreadId.ToString();
            sb.AppendLine(string.Format("①当前线程ID:{0}", thread_id));
            Task<int> t = Async3();//调用异步线程执行
            sb.AppendLine("④/⑤主线程结束.");//直接运行下去   本句和Async1中的“⑤/④当前线程ID。。。”有可能是本句在前打印,也有可能是async1中打印在前,主要是因为是并行执行
            timer1.Enabled = true;      
          //还有一个问题:本实验没有用到t值,比如取值用:t.Result,则会锁死在t.Result这句
      }
      public static int Async1()
      {
            string thread_id = Thread.CurrentThread.ManagedThreadId.ToString();
            sb.AppendLine(string.Format("⑤/④当前线程ID:{0}", thread_id)); //子线程中运行,也就是说Async1函数其实是和UI线程中button1_Click的sb.AppendLine(...)是并行执行的
            int sum = 0;
            for (int i = 0; i < 999; i++)
            {
                sum += i;
            }
            return sum;
      }

      public static async Task<int> Async2()
      {
            string thread_id = Thread.CurrentThread.ManagedThreadId.ToString();
            sb.AppendLine(string.Format("③当前线程ID:{0}", thread_id)); //也是UI线程
            int result = await Task.Run(new Func<int>(Async1));//await标记之后,代码在子线程中执行。
            thread_id = Thread.CurrentThread.ManagedThreadId.ToString();
            sb.AppendLine(string.Format("⑥当前线程ID:{0},result:{1}", thread_id, result)); //UI线程中执行
            return result;
      }

      public static async Task<int> Async3()
      {
            string thread_id = Thread.CurrentThread.ManagedThreadId.ToString();
            sb.AppendLine(string.Format("②当前线程ID:{0}", thread_id)); //UI线程
            int result = await Async2();
            thread_id = Thread.CurrentThread.ManagedThreadId.ToString();
            sb.AppendLine(string.Format("⑦当前线程ID:{0},result:{1}", thread_id, result));//UI线程中执行
            step = 1;
            return result;
      }

      private void timer1_Tick(object sender, EventArgs e)
      {
            if (step > 0)
                timer1.Enabled = false;
            textBox1.Text = sb.ToString();
      }
    }

页: [1]
查看完整版本: Task多线程