关于Thread的一个使用,高手绕道

问题描述:在项目中等待一个线程B的执行结果,如果线程B执行完成,则开始执行主线程。

说实话,关于线程,没有太多的研究,这个只是我的一点小小的体会,说出来,有兴趣的同学一起研究下。

 

step1:创建ScnThread.cs,这是一个执行业务的线程类

public class ScnThread
    {
        public DispatcherTimer Timer { get; set; }

         //是否完成
         public bool IsFinished { get; set; }

        //是否还在处理中
         private bool IsInProcess { get; set; }

        public void IsOverThread()
        {
            IsFinished = false;
            IsInProcess = false;
            Timer = new DispatcherTimer();
            Timer.Interval = TimeSpan.FromMilliseconds(2000);
            Timer.Tick += new EventHandler(Timer_Tick);
            Timer.Start();
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            if (!IsInProcess)
            {
                IsInProcess = true;
                int i = 0;
                while (i < 1000000)//这里是线程中执行业务逻辑的地方,在这里我用循环来代替,表示执行这个业务逻辑需要一点的时间损耗
                {
                    i++;
                }
                IsFinished = true;
            }
            
        }
    }

  这里我们用一个循环来代替实际中可能需要的业务逻辑。这里我们用了IsFinished 和 IsInProcess来记录这个线程的执行情况,IsInPorcess是来记录是否还在线程执行中,如果还在线程执行中,就不进入Timer_Tick中,从而打断业务逻辑的执行。而IsFinished则是用来表示线程是否完成。

我们在MainPage.xmal.cs中,

public partial class MainPage : UserControl
    {
        public DispatcherTimer Timer { get; set; }

        SLControl.ScnThread t = new ScnThread();

        public MainPage()
        {
            InitializeComponent();

            t.IsOverThread();

            Timer = new DispatcherTimer();
            Timer.Interval = TimeSpan.FromMilliseconds(100);
            Timer.Tick += new EventHandler(Timer_Tick);
            Timer.Start();
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            label2.Content = System.DateTime.Now.ToString();

            if (t.IsFinished)
            {
                label1.Content = System.DateTime.Now.ToString();
                t.Timer.Stop();
                Timer.Stop();
            }
        }
    }

  在MainPage我们再创建一个线程,用来检测这个线程是否完成。这样就可以在主线程中来检测ScnThread中线程是否执行完成,如果完成,那就更改Label1的Text,并且停止ScnThread中的线程。

 

 

posted @ 2012-08-23 13:28  海底的鱼  阅读(261)  评论(0编辑  收藏  举报