multithreading - Substitute for async/await when C# form is closing since await never returns? -


this question has answer here:

i have c# windows forms app launches other processes. when form closes, need shutdown processes , make sure they're gone don't hang around zombie processes. strategy send processes shutdown command on socket bridge, , wait them close gracefully. after 3 seconds however, if still around, force close them (kill them).

originally used await task.delay(3000) instruction lived in form's closing event. didn't work. time await task.delay(3000) statement tried return, main thread gone code after statement force closes child processes if they're still around never executed. solve problem changed await task.delay(3000) plain thread.sleep(3000) statement. code following thread.sleep(3000) executes since thread never switched away before.

however, that's 3 seconds app appears unresponsive. technique use instead make sure code after 3 second wait executes, without blocking main ui thread?

in form's closing event, start new thread is:

  • sleep 3 seconds
  • then kills processes

because sleep occurs on separate thread, don't have worry freezing ui. , because thread not background thread, won't go away while sleeps :)

edit:

i ran simple test prove point. after close form, , formclosing event completes, thread still running, , application shuts down after thread wakes , finishes work. crazy?

  private void form1_formclosing(object sender, formclosingeventargs e)   {      thread t = new thread(() =>      {         thread.sleep(10000);         debug.writeline("i still alive!!!  can still kill processes here");         // after point, process shuts down, because last thread running.      });      t.start();       // @ point, form close, process still alive long thread `t` alive.   } 

edit 2:

to whomever feels urge downvote this: @ least take little snippet of code , try before assuming won't work. if fails, downvote me , let me know can learn it.

but stands, @ least did part: tested this, , work.


Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -