简体   繁体   中英

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

I have an application that runs every 15 minutes. I need to add a new task (Maybe a Method) which will be called by the application and should run asynchronously, so the application can complete within the 15 Minutes. If the new task takes longer than the application is running, it will be aborted and can't complete its work. How can I keep a Task running?

There's a few ways you can go about this.

Independent process

The first is, don't run a task, run an independent process that can do the work. The first process will end when it needs to; the worker process will end when it needs to, and there's no communication between them (unless there needs to be for a different reason).

// 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

Now the above means creating two separate executables; one for the launcher and one for the worker. That means two separate projects... or not.

What you can do is have both sets of functionality in the same executable, and invoke the functionality you need by separating it with command-line arguments. In your main you could do:

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
}

I like this approach because you have full isolation due to process boundaries, and yet you don't have to compile and maintain separate projects.

Wait on the main thread

The second way is for the main thread to wait until the worker task is done. Trying to have tasks outlive the main thread can be problematic. Waiting is easy

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

There are, of course, other ways to start background work (eg using Thread ) and for ways for the background work to signal the main thread, but these all require that original thread to wait until the work is done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM