线程等待练习

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Threading.Tasks;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        EventWaitHandle _waitHandle = new AutoResetEvent (false);

        private void button1_Click(object sender, EventArgs e)
        {
            Console.WriteLine("主0");
            //Thread t = new Thread(test);
            //t.Start();

            //Console.WriteLine("主1");
            //t.Join();
            //Console.WriteLine("主2");


            //Thread t1 = new Thread(test);
            //t1.Start();
            //Console.WriteLine("主1");
            //_waitHandle.WaitOne();
            //Console.WriteLine("主2");


            Task task = new Task(tasktest);
            task.Start();

            Console.WriteLine("主1");
            task.Wait();
            Console.WriteLine("主2");

        }


        private void test()
        {
            for (int i = 0; i < 5; i++)
            {
                Thread.Sleep(1000);
            }
            _waitHandle.Set();
            Console.WriteLine("test" + Thread.CurrentThread.ManagedThreadId);
        }

        private void tasktest()
        {
            for (int i = 0; i < 5; i++)
            {
                Thread.Sleep(1000);
            }
           
            Console.WriteLine("test" + Thread.CurrentThread.ManagedThreadId);
        }
    }
}
View Code

 

posted @ 2020-05-04 15:20  安以痕_陈  阅读(68)  评论(0编辑  收藏  举报