前言
报表进行查询操作,方法是使用sql查询或者procedure查询,当时是没有办法在优化sql语句了,然后想到可以将查询结果进行拆分,多次查询拼接起来。然后选用task......
说真的,task真的帮了大忙,大大缩减了执行时间,不过还是要根据需求合理使用,毕竟好东西有利又有弊
1.这里给出两种方法
1.1 Task(Action action) Task构造函数接受的是Action委托
1.2Task<TResult>(Func<TResult> continuationFunction) Task<TResult>接受的是Func<TResult>委托
2.Task(Action action)
举个栗子:
1 static void Main(string[] args) 2 { 3 Console.WriteLine("多线程开始......" + DateTime.Now + DateTime.Now.Millisecond); 4 var desc=new AwaitBll().GetAwaitMesg(); 5 Console.WriteLine(desc.Id+desc.Name); 6 Console.WriteLine("结束......" + DateTime.Now + DateTime.Now.Millisecond); 7 Console.ReadLine(); 8 } 9 public class AwaitBll 10 { 11 Model model = new Model(); 12 public Model GetAwaitMesg() 13 { 14 List<Task> tasks = new List<Task>(); 15 tasks.Add(new Task(() => GetAwaitId(1))); 16 tasks.Add(new Task(() => GetAwaitName("leap"))); 17 foreach (var task in tasks) 18 task.Start(); 19 Task.WaitAll(tasks.ToArray()); 20 return model; 21 } 22 public void GetAwaitId(int id) 23 { 24 model.Id = id; 25 } 26 public void GetAwaitName(string name) 27 { 28 model.Name = name; 29 } 30 }
3.Task<TResult>(Func<TResult> continuationFunction)
同样 举个栗子:
1 static void Main(string[] args) 2 { 3 Console.WriteLine("多线程开始......" + DateTime.Now + DateTime.Now.Millisecond); 4 var desc=new AwaitBll().GetAwaitMesg(); 5 foreach (var item in desc) 6 { 7 Console.WriteLine(item.Id + item.Name); 8 } 9 Console.WriteLine("结束......" + DateTime.Now + DateTime.Now.Millisecond); 10 Console.ReadLine(); 11 } 12 13 public class AwaitBll 14 { 15 public List<Model> GetAwaitMesg() 16 { 17 Task<List<Model>> list = Task.Run(() => GetAwaitPerson()); 18 Task<Model> total = Task.Run(() => GetAwaitTotal()); 19 Task.WaitAll(list, total); 20 var all = list.Result; 21 all.Add(total.Result); 22 return all; 23 } 24 public List<Model> GetAwaitPerson() 25 { 26 List<Model> mlist=new List<Model>(); 27 for (var i = 1; i <=10; i++) 28 { 29 mlist.Add(new Model(i, "leap_" + i)); 30 } 31 return mlist; 32 } 33 public Model GetAwaitTotal() 34 { 35 return new Model(0, "合计"); 36 } 37 }
这里给出简单demo,可以根据自身需求举一反三,原理都是一样的。