using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Threading;
namespace TaskTest2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("任务初始化!");
EventHelper evtHelper = new EventHelper();
Task<bool> mainTask = Task.Factory.StartNew<bool>(() => {
evtHelper.IsRuning = true;
evtHelper.InitTask();
evtHelper.IsRuning = false;
return true;
});
Thread.Sleep(TimeSpan.FromSeconds(5));
Task sonTask = Task.Factory.StartNew(() =>
{
Console.WriteLine("开始子任务!");
evtHelper.DoTask();
Console.WriteLine("任务完成!");
});
Console.ReadLine();
}
}
public class TaskModel
{
public int Index { set; get; }
public string Name { set; get; }
}
public class EventHelper
{
TaskHelper th = new TaskHelper();
public bool IsRuning { set; get; }
/// <summary>
/// 最大并行任务数
/// </summary>
const int MaxThreadNum = 5;
/// <summary>
/// 队列中允许的最大任务数
/// </summary>
const int MaxTaskNum = 30;
int TaskIndex = 0;
public void InitTask()
{
for (int i = 0; i < 2000; i++)
{
TaskModel t = new TaskModel();
t.Index = i + 1;
t.Name = "任务[" + t.Index + "]";
th.AddTask(t);
Console.WriteLine("写入第{0}个任务!",t.Index);
while (th.Count > MaxTaskNum)
{
Console.WriteLine("当前任务队列中的任务数为:{0},超过了允行并行的最大任务数:{1},线程等待中...",th.Count,MaxTaskNum);
Thread.Sleep(TimeSpan.FromSeconds(1));
}
}
}
public void DoTask()
{
while (IsRuning)
{
if (!th.IsQueueActive)
{
Thread.Sleep(TimeSpan.FromSeconds(2));
continue;
}
if (th.Count == 0) break;
Console.WriteLine("队列中有{0}个任务!", th.Count);
Task[] tasks = new Task[MaxThreadNum];
for (int i = 0; i < MaxThreadNum; i++)
{
tasks[i] = new Task(() => {
DoSingleTask(TaskIndex);
});
tasks[i].Start();
}
Task.WaitAll(tasks);
}
}
public void DoSingleTask(object obj)
{
if (th.IsQueueActive)
{
TaskModel tm = th.GetOneTask();
if (tm == null) return;
Console.WriteLine("已经完成任务-----{0}", tm.Name);
Thread.Sleep(TimeSpan.FromSeconds(1));
Interlocked.Increment(ref TaskIndex);
}
}
}
public class TaskHelper
{
public Queue<TaskModel> TaskList = new Queue<TaskModel>();
public void AddTask(TaskModel tm)
{
lock (this)
{
TaskList.Enqueue(tm);
}
}
public TaskModel GetOneTask()
{
lock (this)
{
if (TaskList == null || TaskList.Count == 0) return null;
return TaskList.Dequeue();
}
}
public void ClearList()
{
TaskList.Clear();
}
public bool IsQueueActive
{
get { return TaskList.Count > 0; }
}
public int Count
{
get { return TaskList.Count; }
}
}
}
Task的用法学习(一)
最新推荐文章于 2025-02-10 11:32:21 发布