-5

我得到了这个简单的代码。当单击按钮 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";

}

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

4

1 回答 1

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";

  }
   }

}
于 2013-07-03T21:20:08.527 回答