Pav*_*ari 6 c# multithreading task threadpool task-parallel-library
我正在使用 Task 通过不同的线程创建和执行一些操作,一旦操作完成,我也会回调被调用。
System.Threading.Tasks.Task.Factory.StartNew(() =>
this._httpService.CreateRecord(new Uri(Configuration.Current.CreateRecordUrl), httpObj)).ContinueWith(
(response) =>
{
if (!response.IsFaulted)
{
if (httpObj.CallBack != null)
{
httpObj.CallBack(response.Result);
}
}
else {
this._logger.Error("There was some error which causes the task to fail");
}
});
Run Code Online (Sandbox Code Playgroud)
我的控制台应用程序的主线程不等待任务线程完成,因为它是后台线程。如何使任务线程成为前台线程?
谢谢
您应该等待主线程中的任务完成。
将您的代码更改为
var task = System.Threading.Tasks.Task.Factory.StartNew(() =>
this._httpService.CreateRecord(new Uri(Configuration.Current.CreateRecordUrl), httpObj)).ContinueWith(
(response) =>
{
if (!response.IsFaulted)
{
if (httpObj.CallBack != null)
{
httpObj.CallBack(response.Result);
}
}
else {
this._logger.Error("There was some error which causes the task to field");
}
});
task.Wait(); // Wait till your Task has finished.
Run Code Online (Sandbox Code Playgroud)
Wait() 方法有一些重载来指定等待多长时间。如果任务执行由于取消异常而失败,您还必须添加一些异常处理。
归档时间: |
|
查看次数: |
3851 次 |
最近记录: |