private void button2_Click(object sender, EventArgs e)
{
string btnName = button2.Text;
if (btnName == "启动")
{
isCancel = false;
button2.Enabled = false;
var t = new Task(() => TaskBoot("TaskBoot"));
t.Start();
button2.Text = "停止";
button2.Enabled = true;
}
else
{
isCancel = true;
isComple = true;
button2.Enabled = true;
button2.Text = "启动";
}
}
static void TaskBoot(string name)
{
int taskCount = 5;
taskList = new Task[taskCount];
int taskCurrent;
int rwCount = 20; //要执行总任务数
int rwNum = 0;
while (!isComple)
{
if (isCancel)
{
Console.WriteLine("任务已取消,退出...");
return;
}
for (int i = 0; i < taskCount; i++)
{
if (taskList[i] == null || taskList[i].IsCompleted)
{
if (rwNum >= rwCount)
{
Console.WriteLine("已完成规定数量的所有任务");
isComple = true;
return;
}
rwNum++;
Console.WriteLine("线程:" + Convert.ToString(i) + "开始运行...");
taskList[i] = Task.Factory.StartNew(() => TaskMethod("Task " + Convert.ToString(rwNum)));
}
//加上一点点延时,第一次传递的线程参数才能正确,不会重复。
Thread.Sleep(10);
}
try
{
//Console.WriteLine("正在等待...");
taskCurrent = Task.WaitAny(taskList);
Console.WriteLine("线程:" + Convert.ToString(taskCurrent) + "完成了...");
}
catch (Exception ex)
{
Console.WriteLine("异常信息:" + ex.Message);
//throw;
}
}
Console.WriteLine("所有已完成");
}
static void TaskMethod(string name)
{
Console.WriteLine("Task {0} is running on a thread id {1}. Is thread pool thread: {2}",
name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);
for (int i = 0; i < 3; i++)
{
if (isCancel)
{
Console.WriteLine("已停止");
return;
}
//Console.WriteLine("延时测试" + i.ToString());
Thread.Sleep(1000);
}
//Console.WriteLine("已完成");
}