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

2

10

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?

Thom answered 28/10, 2014 at 16:50 Comment(1)
Can you provide code of the webservice call? Do you use TPL for that?Bravar
B
15

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.

Blodget answered 21/3, 2016 at 8:12 Comment(2)
Thank you sir this was very helpful.Rost
@RahulSonone could be something different about something your code is doing, would be difficult to guess really. Environment.Exit() is designed to close down the processes related to the application, so if there's some sort of persistent process maybe that's causing a problem.Blodget
L
3

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
Lepanto answered 14/8, 2018 at 18:20 Comment(1)
i assume there is a missing closing braket, paranthesis and semicolon on the end of the code block?Schooner

© 2022 - 2024 — McMap. All rights reserved.