1、Task举例
1.案例场景,现在有server有一个不固定数的任务请求,假设是个,但是做的是相同的事情。简而言之就是根据server端的请求个数来到Client来动态的开线程,调用Client的程序逻辑。
方式一:
List taskList = new List();
for (int i = 0; i < list.Count; i++)
{
System.Threading.Tasks.Task aTask =
taskFactory.StartNew(() =>
{
Coding(i, i + new Random().Next(1, 10));
});
System.Threading.Thread.Sleep(100);
taskList.Add(aTask);
}
方式二
TaskFactory taskFactory = new TaskFactory();
Stopwatch sw = new Stopwatch();
List list = new List() { 1, 2, 3, 4, 5, 6, 7, 8 };
List taskList = new List();
for (int i = 0; i < list.Count; i++)
{
System.Threading.Tasks.Task aTask =
taskFactory.StartNew((x) =>
{
Coding((int)x, (int)x + new Random().Next(1, 10));
}, i);
System.Threading.Thread.Sleep(100);
taskList.Add(aTask);
}
Task.WaitAll(taskList.ToArray());
Console.WriteLine("所有Task执行完毕");
Console.ReadKey();
以上两种方式的执行结果,问题很大,没把我整死。主要也是自己菜。
static int Coding(int name, int content)
{
int k = name;
Console.WriteLine("当前K : " + k + DateTime.Now.ToString("yyyy-mm-dd:HH:mm:ss:ffff"));
int delay = new Random().Next(100,10000);
System.Threading.Thread.Sleep(delay);
int s = k + content;
Console.WriteLine("第" + k + "次,完成了" + "延时了" + delay);
//System.Threading.Thread.Sleep(100);
return s;
}
线程并行也可以实现 Parallel
List list = new List() { 1, 2, 3, 4, 5, 6, 7, 8 };
int k = list.Count();
ParallelLoopResult result = Parallel.For(0, k, x =>
{
System.Threading.Thread.Sleep(100);
Coding(list[x], x + new Random().Next(1, 10));
});
while (result.IsCompleted)
{
Console.WriteLine("ttt");
break;
}
记录线程并行的情况下,8个线程同时启动的时间差异;
时间有限,就这样了!