简体   繁体   中英

What happens with running tasks when Window close?

I have three pages:

Page1 inherit from Window class. Page2 and Page3 inherits from UserControl class.

When i go from Page1 to Page2 i dispose two long disposing objects with two Tasks :

var task1 = Task.Factory.StartNew(() => MyObject1.Dispose());
var task2 = Task.Factory.StartNew(() => MyObject2.Dispose());
List<Task> tasks = new List<Task>();
tasks.Add(task1);
tasks.Add(task2);
//    Task.WaitAll(tasks.ToArray()); 

The same code on Page2 and 3. What happens if user close Page1,2 or 3? Will my tasks run anyway when Page is closing? Or it break too? Shound i use Dispatcher instead of Task ?

Thank you!

Impossible to say precisely without a good, minimal , complete code example . It depends on what else happens when the window closes. In general, if the process is still alive, so too will the tasks be. The window doesn't "own" the tasks per se, nor would closing it cause any of those tasks to be interrupted.

But TaskFactory.StartNew() runs your delegate invocation in the thread pool. And background threads (like those in the thread pool) are terminated, along with the process itself, when there are no longer any foreground threads in the process. If closing your window causes the sole foreground thread in the process to exit, then your tasks all stop, along with the rest of the process.

In between those two scenarios, there are lots of other possibilities. All of the above assumes your own code does nothing to attempt to interfere with the default mechanisms. If these two explanations don't seem to apply in your case, please provide a good code example and clarify your question.

Will my tasks run anyway when Page is closing?

If your question is "are my tasks rooted somewhere such that when garbage collection starts, they will not be eligable for collection" then the answer is yes, asssuming your process does not terminate by closing it's foreground thread that runs the message loop.

The tasks are queued on the thread-pool, which keeps a reference to them, or if they are already executing then the they're rooted by the thread's stack, which will keep them alive until they complete.

I would say this: If you need to execute your IDisposable.Dispose method on a background thread, I'd say you're doing something inherently wrong . A dispose method should be no more then the disposal of unmanaged resources.

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