Dean
Dean

Reputation: 1550

'System.Threading.Tasks.TaskCanceledException' occurred in WindowsBase.dll when closing application

I have this property in my viewmodel.

public bool IsKWH
{
    get { return _isKwh; }
    set
    {
        if (value.Equals(_isKwh)) return;
        _isKwh = value;
        NotifyOfPropertyChange(() => IsKWH);
    }
}

Sometimes (~1 in 10 times) when I close down my application I get the following error in NotifyOfPropertyChange:

An exception of type 'System.Threading.Tasks.TaskCanceledException' occurred in WindowsBase.dll but was not handled in user code

Additional information: A task was canceled.

I have a System.Threading.Timer in my view model that is making a webservice call to update this and many other properties.

I am using Caliburn.Micro and it seems to have started happening when I updated from 1.5 to 2.0.

Is there anyway to prevent this error from occurring?

Upvotes: 10

Views: 9223

Answers (2)

Marteen
Marteen

Reputation: 31

FWIW, that fix didn't help me. the problem was coming from a 3rd party DLL that's dynamically loaded. I was unable to stop the exception from getting thrown, however I ignore the exception in the app exception handler:

AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(
                (sender2, args) =>
                {
                    Exception ex = (Exception)args.ExceptionObject;  
                    // unloading dragon medical one
                    if (ex is TaskCanceledException)  
                        return;  // ignore

Upvotes: 3

JoeTomks
JoeTomks

Reputation: 3276

It is possible that intermittently your application fails to dispose of any secondary threads that it is using before the application closes. This can often cause an error message such as the one you posted. Could I suggest trying the following:

protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
       // close all active threads
       Environment.Exit(0);       
}

This should force the application to terminate all active threads before it closes. I recall having a similar problem and that particular little fix solved it. Might be worth giving it a try, let me know if it doesn't help and we can see what other solutions there might be. Hope this works for you.

Upvotes: 15

Related Questions