日期:2014-05-18  浏览次数:20887 次

如何设置线程完全结束后运行其他内容?
C# code

public delegate void delegateHandle(object sender,EventArgs e);

public partial class FCPMClient : Form
{
   public event delegateHandle onFinished;
   private Thread thread = null;

   public FCPMClient()
   {
      InitializeComponent();
   }

   private void Form1_Load(object sender, EventArgs e)
   {
      thread = new Thread(new ThreadStart(fun1));
      thread.Start();
      this.onFinished += new delegateHandle(fun2);
   }

   private void fun1(){
      onFinished(this, new EventArgs());
   }

   private void fun2(object sender, EventArgs e){
      thread.Abort();
   }
}



我现在的需求是在某一个线程结束后运行某些代码,但我的程序类似上边这些,调用 fun2 时,实际上线程还在进行,并没有完全结束,这个要怎么解决?

------解决方案--------------------
看你想怎么用多线程序:
1.如果是compute bound,用Task.ContinueWith或TaskFactory.ContinueXXXXXX
(1).参考:http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.continuewith.aspx
(2).http://msdn.microsoft.com/en-us/library/dd321446.aspx
2.如果是用BeginXXX,EndXXX,就用callback.
------解决方案--------------------
[code=c#]
public delegate void delegateHandle();

public partial class FCPMClient : Form
{
public event delegateHandle onFinished;
private Thread thread = null;

public FCPMClient()
{
  InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
  thread = new Thread(new ThreadStart(fun1));
  thread.Start();
  label1.Text = "线程开始";
}

private void fun1(){
  Thread.Sleep(3000);
  onFinished  mi = new onFinished(fun2);
}

private void fun2(){
  label1.Text = "线程结束";
}
}
[/code]
------解决方案--------------------
private Thread thread = null;这句没用,去掉
C# code
 
public delegate void delegateHandle();

public partial class FCPMClient : Form
{
   public event delegateHandle onFinished;

   public FCPMClient()
   {
      InitializeComponent();
   }

   private void Form1_Load(object sender, EventArgs e)
   {
      thread = new Thread(new ThreadStart(fun1));
      thread.Start();
      label1.Text = "线程开始";
   }

   private void fun1(){
      Thread.Sleep(3000);
      onFinished  mi = new onFinished(fun2);
   }

   private void fun2(){
      label1.Text = "线程结束";
   }
}