如果我可以并行运行多个Task.Factory.StartNew语句,请告诉我.
有点像这样
var task = Task.Factory.StartNew<List<AccessDetails>>(() => this.GetAccessListOfMirror(mirrorId,null,"DEV")); var task1 = Task.Factory.StartNew<List<AccessDetails>>(() => this.GetAccessListOfMirror(mirrorId,"PROD"));
我之前使用过如下的声明.应用程序将等待直到我从线程获得输出.
var task = Task.Factory.StartNew<List<AccessDetails>>(() => this.GetAccessListOfMirror(mirrorId,"DEV")); return (List<AccessDetails>)task.ContinueWith(tsk => accdet = task.Result.ToList()).Result;
解决方法
您可以让多个任务运行,并等待所有这些任务完成,如下所示:
var task = Task.Factory.StartNew<List<AccessDetails>>(() => this.GetAccessListOfMirror(mirrorId,"DEV")); var task1 = Task.Factory.StartNew<List<AccessDetails>>(() => this.GetAccessListOfMirror(mirrorId,"PROD")); var allTasks = new Task[]{task,task1}; Task.WaitAll(allTasks); var result = task.Result; var result1 = task1.Result;
如果您只想等待第一个完成,可以使用Task.WaitAny作为示例.