C#使任务线程前景



我正在使用任务来创建和执行其他线程的操作,一旦操作完成,我也叫回电。

 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");

                       }
                   });

我的控制台应用程序的主线程没有等待任务线程完成,因为它是背景线程。如何使任务线程前景线程

谢谢

StartNew()方法返回 Task实例。在返回任务上调用Wait()方法将阻止主线程直到任务完成。

static void Main(string[] args)
{
    var task = Task.Factory.StartNew(() =>
    {
        // ...
    });
    task.Wait(); // The main application thread waits here until the task returns
}

我的控制台应用程序的主线程没有等待任务线程完成,因为它是背景线程。

您的应用程序不在等待任务,因为您不告诉它这样做。

正如其他人已经说过的,请使用Wait/Resultawait等待任务,具体取决于您是否处于异步上下文。

如何使任务线程前景线程。

很可能您不想首先这样做。A 背景线程是一个线程,当所有前景线程结束时终止。线程池线程本质上是背景线程,如果您实际上想安排任务到 em> foreground 线程,即即使在主线程已经完成,您必须创建自己的TaskScheduler。顺便说一句,这将是使用Task.Factory.StartNew的原因。如果您不需要 Task.Factory.StartNew,请选择Task.Run

您应该等待主线程中的任务完成。

将您的代码更改为

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.

Wait()方法具有一些过载,可以指定等待多长时间。另外,如果由于取消的例外,如果任务执行失败,则必须添加一些异常处理。

尝试创建一个新的新线程,而不是从池中取走。例如:

Thread t = new Thread(()=> 
{
    //all your code goes here
});
t.IsBackground = false; //by default it will be foreground. so don't need this line in your case
t.Start();

这将为您创建一个前景线程,并确保线程完成其执行。

最新更新