如何在主线程结束后保留​​一个任务运行?

How to keep a task running after the main thread ends?

我有一个应用程序 运行 每 15 分钟一次。我需要添加一个新任务(可能是一个方法),该任务将由应用程序调用并且应该 运行 异步,以便应用程序可以在 15 分钟内完成。如果新任务花费的时间超过应用程序 运行ning 的时间,它将被中止并且无法完成其工作。如何保留任务 运行ning?

有几种方法可以解决这个问题。

独立进程

首先是,不要运行一个任务,运行一个可以完成工作的独立进程。第一个进程将在需要时结束;工作进程将在需要时结束,并且它们之间没有通信(除非出于其他原因需要)。

// in main thread...
var process = new Process(); // create the process
...
process.Start();
// process.WaitForExit(); this is commented out because you want main process to end without waiting
// main then ends here

现在上面的意思是创建两个独立的可执行文件;一个用于发射器,一个用于工作人员。这意味着两个独立的项目......或不是。

您可以做的是在同一个可执行文件中拥有两组功能,并通过将其与命令行参数分开来调用您需要的功能。在您的主要工作中,您可以这样做:

static void Main(string[] args)
{
   if (args.Length == 1 && args[0] == "worker")
      DoWorkerStuff();
   else
   {
      var process = new Process(); // create the process
      ...
      // use process API to call yourself with the arg
      process.Start();
      // process.WaitForExit(); this is commented out because you want main process to end without waiting
   }

    // main then ends here for both the launcher and the worker
}

我喜欢这种方法,因为由于进程边界,您可以完全隔离,而且您不必编译和维护单独的项目。

在主线程上等待

第二种方式是主线程等待worker任务完成。试图让任务比主线程活得更久可能会有问题。等待很简单

    // in main thread...
    var task = ... // however you create the task
    ...
    task.Wait(); // or one of the other Wait() overloads

当然,还有其他方法可以启动后台工作(例如使用 Thread)以及后台工作向主线程发送信号的方法,但这些都需要原始线程等待直到工作完成。