懒得写麻烦的demo了,给你写一个console的例子:这里你可以看到,开始一个线程操作跟随后在另一个线程中“继续处理”,是如何配合的。using System; using System.Threading;namespace ConsoleApplication1 { class Program { static void Main(string[] args) { var t = new TestProgram(); while (true) { var k = Console.ReadKey(); if (k.KeyChar == 'A' || k.KeyChar == 'a') t.CreateTask("tsk_" + (++n)); else if (k.KeyChar == 'B' || k.KeyChar == 'b') t.Continue(); } } static int n; } public class TestProgram { public event EventHandler Fire; public void CreateTask(string ttl) { ThreadPool.QueueUserWorkItem(h => { Console.WriteLine("\r\n先执行前半部分,在一个线程中注册任务“{0}”,并且等待按下键盘b键........", ttl); var t = new MyTask { title = ttl, theTime = DateTime.Now }; Fire += t.继续; }); } public void Continue() { if (Fire != null) Fire(this, null); } } public class MyTask { public string title; public DateTime theTime; public void 继续(object sender, EventArgs e) { var tp = (TestProgram)sender; tp.Fire -= 继续; ThreadPool.QueueUserWorkItem(h => { Thread.Sleep(1000); Console.WriteLine("\r\n1秒过后,在另一个线程中完成了任务“{0}”(是{1}开始的任务)。", title, theTime); }); } } }
Thread T = new Thread(f);
T.Start()
T.Suspend() //程序执行到这里 挂起线程//失去焦点的时候恢复线程
T.Resume() //怎么样才能让线程恢复过后再执行下面这句输入语句 如果没恢复则不执行MessageBox.Show("子线程完成的工作");
void f()
{
MessageBox.Show("子线程完成的工作");
}
AutoResetEvent detailCollectedEvent = new AutoResetEvent(false); ------------------//在想停的地方加上这句
detailCollectedEvent.WaitOne();
---------------------
//输入完值后可以使用这句:继续执行
detailCollectedEvent.Set();
多线程编程通常不需要阻塞。只有用线程的语法去模拟顺序执行的人,才会动不动就阻塞。如果一个程序的连续操作它“断开”,那么就应该断开。例如一个线程可能去设置监听环境对象(为这个对象设置各种初始值),然后向dataGridView的单元格改变事件注册为这个监听对象的某个方法,然后这个线程就结束了!等dataGridView的单元格修改了,这个方法可以被触发执行。如过你愿意,这个方法里边可以再启动另外一个线程来进行所谓“继续执行下面的语句”(因为之前的那个线程的运行结果状态已经被记录到监听对象中了,因此这你可以继续执行处理)。这里可以看出,根本不存在什么阻塞!根本没有什么线程在哪里“没事阻塞”着,而都是100%地干正经事的线程执行。如果你阻塞了,那么你可以想象出,你得能搞多少线程才够?
using System.Threading;namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var t = new TestProgram();
while (true)
{
var k = Console.ReadKey();
if (k.KeyChar == 'A' || k.KeyChar == 'a')
t.CreateTask("tsk_" + (++n));
else if (k.KeyChar == 'B' || k.KeyChar == 'b')
t.Continue();
}
} static int n;
} public class TestProgram
{
public event EventHandler Fire; public void CreateTask(string ttl)
{
ThreadPool.QueueUserWorkItem(h =>
{
Console.WriteLine("\r\n先执行前半部分,在一个线程中注册任务“{0}”,并且等待按下键盘b键........", ttl);
var t = new MyTask
{
title = ttl,
theTime = DateTime.Now
};
Fire += t.继续;
});
} public void Continue()
{
if (Fire != null)
Fire(this, null);
}
} public class MyTask
{
public string title; public DateTime theTime; public void 继续(object sender, EventArgs e)
{
var tp = (TestProgram)sender;
tp.Fire -= 继续;
ThreadPool.QueueUserWorkItem(h =>
{
Thread.Sleep(1000);
Console.WriteLine("\r\n1秒过后,在另一个线程中完成了任务“{0}”(是{1}开始的任务)。", title, theTime);
});
}
}
}