开发者

AppDomain.CurrentDomain.ProcessExit and cleanup

开发者 https://www.devze.com 2022-12-17 00:50 出处:网络
I have simple application when I need to stop a background thread using Stop() function before application is closed. The problem is that my Main() f开发者_运维问答unction has several exit points (ret

I have simple application when I need to stop a background thread using Stop() function before application is closed. The problem is that my Main() f开发者_运维问答unction has several exit points (return statements)

static void Main(string[] args)
{
/// some code
return;

// some code
return;

//// etc
}

I tried to use AppDomain.CurrentDomain.ProcessExit as a single place for clean up but it is never called (at least while there is a background thread). Is there a way to work out some nice way to implement that?


You can wrap all you code in a separate method and call it from Main():

static void Main(string[] args)
{
  DoSomething();
  TerminateThread(); // Thread.Stop() code goes here
}

static void DoSomething()
{
   /// some code
   return;

   // some code
   return;

   //// etc
}


Change the return; calls and call a cleanup routine that also terminated the process.


You can use Application.ApplicationExit Event

According to MSDN the event:

Occurs when the application is about to shut down.

0

精彩评论

暂无评论...
验证码 换一张
取 消