无法在已完成的任务上调用start

时间:2013-07-03 18:49:21

标签: c# task

我得到了这个简单的代码。单击按钮DoSomething(),DoSomethingElse()和DoEvenMore()运行良好,我等待它完成。

void Button1Click(object sender, System.EventArgs e)
{
   Task one = new Task(() => DoSomething());
   Task two = new Task(() => DoSomethingElse());
   Task three = new Task(() => DoEvenMore());

   one.start();
   two.start();
   three.start();
}

void DoSomething()
{
   label1.Text = "One started";

}

void DoSomethingElse()
{
   label1.Text += "Two started";

}

void DoEvenMore()
{
   label1.Text += "Three started";

}

现在,如果我在没有退出程序的情况下再次单击该按钮,我将获得带有上述meessage的InvalidOperationException。我应该怎么做才能每次单击按钮而不必退出程序时执行相同的任务?

1 个答案:

答案 0 :(得分:1)

此代码适用于我,我可以多次单击该按钮而不会在标题中抛出错误:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
   public partial class Form1 : Form
   {
      public Form1()
      {
         InitializeComponent();
      }

  void Button1Click(object sender, System.EventArgs e)
  {
     Task one = new Task(() => DoSomething());
     Task two = new Task(() => DoSomethingElse());
     Task three = new Task(() => DoEvenMore());

     one.Start();
     two.Start();
     three.Start();
  }

  void DoSomething()
  {
     if (InvokeRequired) Invoke((MethodInvoker)delegate { DoSomething(); });
     else label1.Text = "One started";

  }

  void DoSomethingElse()
  {
     if (InvokeRequired) Invoke((MethodInvoker)delegate { DoSomethingElse(); });
     else label1.Text += "Two started";

  }

  void DoEvenMore()
  {
     if (InvokeRequired) Invoke((MethodInvoker)delegate { DoEvenMore(); });
     else label1.Text += "Three started";

  }
   }

}