I am creating application with feature that open new window inside my application and starting additional processes and tasks inside them. I am realized that when we trying open and close window to often (less than one second per reopening) some tasks wasn't canceled and some processes as I wanted.
For canceling tasks and processes I use CancellationTokenSource
, CancellationToken
which one I Cancel()
and Dispose()
in Window.Closed [Event]
.
But if I will reopening my window too often its say me that Task was canceled or disposed.
So, How I can start my Tasks in Window constructor and closed correctly them when window closing?
Code:
MyAdditionalWindowClass
{
private CancellationTokenSource source;
private CancellationToken token;
private Process process;
MyAdditionalWindowClass()
{
source = new CancellationTokenSource();
token = source.Token;
Start();
thiswindow.Closed = (sender, e) => { process?.Kill(); process?.Close(); source.Cancel(); source.Dispose(); };
}
private async void Start()
{
await Task.Run(ToDoSomething), token);
//and other code after await
}
private void ToDoSomething()
{
//creating process, start him, do something
}
}
CodePudding user response:
public void ExitApp()
{
Application.Exit();
}
How about closing the window using this method?
CodePudding user response:
Your application should ask all components to close nicely when the user exits an application. Usually done by calling the Dispose method on any components that is disposable.
It the component has some background task it should tell this task to exit when it is disposed, for example by using a cancellation token, but there are other methods, like completing a blocking queue. Ideally you should use IAsyncDispose since that lets your dispose method return the task, so the caller can await it. If that is not available you need to decide if you can safely wait for the task, or if it is better to return before you are certain the background task has completed.
If the background task involves any IO you should wait for it to complete, otherwise you risk aborting in the middle of a write. If there is no IO involved, waiting is less important since the OS will cleanup the memory anyway.