目标:当子线程A运行完后,才继续运行主线程。
主要方法:使用ManualResetEvent对象。来操作线程的等待和重启。
注意: allDone.Reset(); allDone.WaitOne();放置的位置。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace text1
{
class TextClass2
{
static string _TextOut;
ManualResetEvent allDone = new ManualResetEvent(false);
public void Start()
{
Thread thread = new Thread(new ThreadStart(Moni));
thread.Start();
allDone.Reset();
allDone.WaitOne();//让线程处于等待状态。
}
public void Moni()
{
for (; ; )
{
Random rdm = new Random();
int a = rdm.Next(0, 888);
if (a > 800)
{
TextOut = a.ToString();
allDone.Set();//重启唤醒线程
break;
}
}
}
public static string TextOut
{
get { return _TextOut; }
set { _TextOut = value; }
}
}
}
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;
namespace text1
{
public partial class Form1 : Form
{
//public static ManualResetEvent allDone = new ManualResetEvent(false);
System.Threading.Timer timer;
public Form1()
{
InitializeComponent();
// Control.CheckForIllegalCrossThreadCalls = false;
}
private void button1_Click(object sender, EventArgs e)
{
button1.BackColor = Color.Black;
TextClass2 textClass2 = new TextClass2();
textClass2.Start();
textBox2.Text = TextClass2.TextOut;
}
}
}