无法对已完成的任务调用start
本文关键字:任务 调用 start 已完成 | 更新日期: 2023-09-27 18:20:50
我得到了这个简单的代码。当单击按钮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,并显示上面的消息。我应该怎么做才能在每次单击按钮时执行相同的任务,而不必退出程序?
这段代码对我有效,我可以多次点击按钮,而不会在标题中引发错误:
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";
}
}
}