Task的用法
2.1、创建任务
无返回值的方式
方式1:
var t1 = new Task(() => TaskMethod("Task 1"));
t1.Start();
Task.WaitAll(t1);//等待所有任务结束
注:
任务的状态:
Start之前为:Created
Start之后为:WaitingToRun
方式2:
Task.Run(() => TaskMethod("Task 2"));
方式3:
Task.Factory.StartNew(() => TaskMethod("Task 3")); 直接异步的方法
或者
var t3=Task.Factory.StartNew(() => TaskMethod("Task 3"));
Task.WaitAll(t3);//等待所有任务结束
注:
任务的状态:
Start之前为:Running
Start之后为:Running
实际应用:
public ActionResult FinSave(EquipMaster model)
{
new Task(StartCode, model.EquipID).Start();
//var t1 = new Task(() => StartCode(model.EquipID));
//t1.Start();
return Json(rx);
}
private static void StartCode(object EquipID)
{
try
{
BaseManager bm = new BaseManager();
var sql = @"exec sp_ExportFAJDENew '" + EquipID + "'";
var rx = bm.ExecuteCommand(sql);
JeffSoft.Logger.Error(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") +"sp_ExportFAJDENew sucess:" + EquipID );
}
catch (Exception e)
{
JeffSoft.Logger.Error(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "sp_ExportFAJDENew sucess:" + EquipID, e);
}
}