我想问一下,如何实现动态的分配或关闭线程。例如,我点击button1则自动打开一个新的线程执行文件删除操作,而我点击button2则又自动打开另一个新的线程返回计算机的当前日期?

解决方案 »

  1.   

    可以通过代理的异步调用来完成你的调用。
    AsyncDelegate AsyncResult
    异步委托提供以异步方式调用同步方法的能力。当同步调用一个委托时,Invoke 方法直接对当前线程调用目标方法。如果编译器支持异步委托,则它将生成 Invoke 方法以及 BeginInvoke 和 EndInvoke 方法。如果调用 BeginInvoke 方法,则公共语言运行库将对请求进行排队并立即返回到调用方。将对来自线程池的线程调用该目标方法。提交请求的原始线程自由地继续与目标方法并行执行,该目标方法是对线程池线程运行的。如果已经对 BeginInvoke 指定了回调,当目标方法返回时将调用它。在回调中,使用 EndInvoke 方法来获取返回值和输入/输出参数。如果没有对 BeginInvoke 指定回调,则可以在提交请求的原始线程上使用 EndInvoke。
      

  2.   

    using System.Runtime.Remoting.Messaging;private void button1_Click(object sender, System.EventArgs e)
    {
        MessageBox.Show("GetDate process is begin.");
        GetDateDelegate gd = new GetDateDelegate(this.GetCurrentDate);
        gd.BeginInvoke(new AsyncCallback(this.CallbackMethod),null);
    }private void CallbackMethod(IAsyncResult iar)
    {
        AsyncResult ar = (AsyncResult) iar;
        GetDateDelegate gd = (GetDateDelegate) ar.AsyncDelegate;
        string msg = gd.EndInvoke(iar);
        MessageBox.Show(msg);
    }public delegate string GetDateDelegate();
      

  3.   

    private string GetCurrentDate()
    {
        System.Threading.Thread.Sleep(5000);
        return DateTime.Now.ToString();
    }
      

  4.   

    using System.Threading;
    private Thread thread;
    private void button1_Click(object sender, System.EventArgs e)
    {
                            thread=new Thread(new ThreadStart(shanchu));

    }
    private void button2_Click(object sender, System.EventArgs e)
    {
                            thread=new Thread(new ThreadStart(datatime));

    }
    private void shanchu()
    {
      //编写文件删除操作的代码
    }
    private void datatime()
    {
      //编写返回计算机的当前日期的代码
    }
      

  5.   

    写掉了,现在补上
    using System.Threading;
    private Thread thread;
    private void button1_Click(object sender, System.EventArgs e)
    {
                            thread=new Thread(new ThreadStart(shanchu));
                            thread.Start();

    }
    private void button2_Click(object sender, System.EventArgs e)
    {
                            thread=new Thread(new ThreadStart(datatime));
          thread.Start();
    }
    private void shanchu()
    {
      //编写文件删除操作的代码
    }
    private void datatime()
    {
      //编写返回计算机的当前日期的代码
    }
      

  6.   

    比较同意 wang2034(HOH) 方法