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

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?

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.

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

Related

An unhandled exception of type 'System.ExecutionEngineException' occurred in WindowsBase.dll

I'm getting an exception that occurs in WindowsBase.dll when desktop switch event happens. I have an WPF application that sets the system events, and then run the other stuff on the different thread.
// SYSTEM EVENT WATCHER
_log.LogInformation("Setting session and desktop event watcher");
_systemEventWatcher.SessionSwitchEvent += SystemEventWatcher_SessionSwitchEvent;
_systemEventWatcher.SessionEndingEvent += SystemEventWatcher_SessionEndingEvent;
_systemEventWatcher.DesktopSwitchEvent += SystemEventWatcher_DesktopSwitchEvent;
_systemEventWatcher.SetSystemWatcher();
_ = Task.Run(async () =>
{
var manifestJson = await _manifestDownloader.DownloadManifestAsync();
if (!await _moduleService.InitializeAsync(manifestJson))
{
TokenSource.Cancel();
}
});
At this moment there is no UI involved. Once desktop switch happens for example pressing CTR - ALT - DEL. When event happens app just breaks producing An unhandled exception of type 'System.ExecutionEngineException' occurred in WindowsBase.dll without even triggering event handler.
Interestingly, if I comment part where Task.Run is called, everything works as it should. If anyone have any ideas, why it is happening, would be interesting to know.
I have tried to run the code using Thread.Start method, but same thing happening. Don't really know what else to try.
Thank you in advance.

Unload child AppDomain that contains POS hardware causing CannotUnloadAppDomainException

I am using .net 4.0, with POS.net 1.12 and I create a hardware class in a new child AppDomain so that any unhandled exceptions do not kill my parent AppDomain.
I can create the child AppDomain and make calls to it no problem. However, if I try to unload the AppDomain I get the exception "CannotUnloadAppDomainException".
I have googled the issue and the exception normally occurs when threads cannot be killed. I do not actually create any new threads in the child class.
I managed to pinpoint the piece of code that causes this error. If I create the POS hardware class and it only creates POS objects then it works fine. If, however, I call method "Open()" on any piece of hardware, then this exception occurs when unloading. Now before I attempt the unload, I close down all hardware and I have made sure the clean up code gets hit, so I am unsure what the issue is.
Here is the code to create and unload the AppDomain:
AppDomain hardwareDomain = AppDomain.CreateDomain("Hardware domain");
IHardwareManager hardwareManager =
(IHardwareManager)hardwareDomain.CreateInstanceFromAndUnwrap(typeof(OposHardwareManager).Assembly.Location,
typeof(OposHardwareManager).FullName);
hardwareManager.StartupHardware();
hardwareManager.CloseDownHardware();
hardwareManager = null;
// **** causes exception
AppDomain.Unload(hardwareDomain);
And here is the hardware class:
public class OposHardwareManager : MarshalByRefObject, IHardwareManager
{
private PosExplorer _posExplorer;
private PosPrinter _printer;
public void StartupHardware()
{
// create the hardware explorer
this._posExplorer = new PosExplorer();
// create and enable the printer
DeviceInfo printerInfo = this._posExplorer.GetDevice(DeviceType.PosPrinter);
PosDevice printerDevice = this._posExplorer.CreateInstance(printerInfo);
this._printer = (PosPrinter)printerDevice;
// ***** this line here, if run, causes the exception on unload
this._printer.Open();
this._printer.Claim(2000);
this._printer.DeviceEnabled = true;
}
public void CloseDownHardware()
{
this._printer.Release();
this._printer.Close();
this._printer = null;
this._posExplorer = null;
}
}
Any ideas?
If you are referencing a type in your creating domain (like you do with typeof(OposHardwareManager)), the assembly will be loaded in that domain too. When that happens, iow types crossing the domain boundary 'upwards', the created domain cannot be unloaded.
I suggest you do not reference the assembly containing OposHardwareManager and simply create it with the full qualified name instead. This may involve some refactoring.
In the documentation of AppDomain.Unload it is remarked that:
If a thread does not abort, for example because it is executing
unmanaged code, or because it is executing a finally block, then after
a period of time a CannotUnloadAppDomainException is thrown in the
thread that originally called Unload.
This is probably your case. Look at the documentation of PosDevice on how to properly release the resource.
Also note that an unhandled exception thrown by a thread created in the new AppDomain will crash your whole application. In the documentation of AppDomain.UnhandledException Event it is remarked that:
In the .NET Framework versions 1.0 and 1.1, an unhandled exception
that occurs in a thread other than the main application thread is
caught by the runtime and therefore does not cause the application to
terminate. Thus, it is possible for the UnhandledException event to be
raised without the application terminating. Starting with the .NET
Framework version 2.0, this backstop for unhandled exceptions in child
threads was removed, because the cumulative effect of such silent
failures included performance degradation, corrupted data, and
lockups, all of which were difficult to debug.
Not sure would this help but I founded the same error on Win 7 and XP. During app exit then the app crashed and error thrown. But the fault came from Report Viewer so when unload the form please make sure call
reportviewer.Reset();

How can I get WinForms to stop silently ignoring unhandled exceptions?

This is getting extremely irritating. Right now I have a winforms application, and things were not working right, but no exceptions were being thrown as far as I could tell. After stepping through almost all pieces of relevant code, it turns out that an exception was being thrown at the start of my application.
Long story short, in WinForms, being as awesome as it is, if an exception occurs the WinForms library ignores it. No "an unhandled exception has occurred" JIT message is thrown, it just stops processing the current event and goes back to the GUI.
This is causing random bugs, because code to load data isn't being called due to the exception occurring prior to this data being loaded.
To see this in action I created a brand new WinForms application, and entered the following code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string blah = null;
blah.Trim();
}
}
Press F5 and the form loads without any errors showing, even though a null reference is being thrown.
I then tried to go to my Program.cs main method and add Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException); to it. Still my form loads without causing any errors to be thrown.
Even though I know that I can tell VS to break on all exceptions, I find this situation really bad. It causes really wierd issues that are hard to debug in production, and as this is an internal tool I really want to have it so it actually errors out when an exception occurs, and not silently disregards it.
Does anyone know how to do this?
Update: Just to update on things I have learned from the comments.
This does appear to be a 64-bit issue with windows, as I learned from this question which I did not see before posting. In that question it pointed to a Microsoft bug report about this, which had this to say:
Hello,
This bug was closed as "External" because this behavior results from how x64 version of Windows handle exceptions. When a user mode exception crosses a kernel transition, x64 versions of Windows do not allow the exception to propagate. Therefore attached debuggers are unaware of the fact that an exception occured resulting in the debugger failing to break on the unhandled exception.
Unfortunately where is nothing that the Visual Studo team can do to address this, it is the result of operating system design. All feedback regarding this issue should be addressed to the Windows team; however the Windows team considers this to be the "correct" operating system design, and considers the x86 behavior to be "incorrect".
Best Regards,
Visual Studio Debugger
That being said, builds not run through visual studio (or using Ctrl+F5 to run) does seem to show the JIT exception message box EXCEPT if you have the following code in your Program.cs:
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);
That code will cause windows to ignore the exception.
However, if you (instead) subscribe to the Application.ThreadException event, not only will your exceptions be caught, visual studio's debugger will break on unhandled exceptions!
In your Program.cs' Main function you should also ensure that you've wrapped your call to open the form in a try/catch. Additionally use the AppDomain.UnhandledException to catch exceptions. We also add Application.ThreadException too.
I believe the following will give you hooks into all the exceptions that can be thrown...
static void Main()
{
try
{
System.Windows.Forms.Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
System.Windows.Forms.Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(OnGuiUnhandedException);
AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
var form = new MainForm();
form.ShowDialog();
}
catch (Exception e)
{
HandleUnhandledException(e);
}
finally
{
// Do stuff
}
}
private static void HandleUnhandledException(Object o)
{
// TODO: Log it!
Exception e = o as Exception;
if (e != null)
{
}
}
private static void OnUnhandledException(Object sender, UnhandledExceptionEventArgs e)
{
HandleUnhandledException(e.ExceptionObject);
}
private static void OnGuiUnhandedException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
HandleUnhandledException(e.Exception);
}
Try the following.
Handle exceptions in your main application entry point.
Also, manage unhandled thread exceptions using a ThreadExceptionEventHandler
This is the code snippet:
[STAThread]
public static void Main(string[] args)
{
try
{
Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
//your program entry point
}
catch (Exception ex)
{
//manage also these exceptions
}
}
private void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
ProcessException(e.Exception);
}
An easy fix is not to run under the debugger.
The debugger is masking the exception for some reason. If you run your app normally (Ctrl+F5), you'll get the usual "Unhandled exception has occurred in your application... Continue/Quit?" dialog.
Having experienced this often and identified the issue regarding 64 bit OS and the Form.Load event, I always just make a point of doing all my start up functions in the Form.Shown event. For all practical purposes this is the same thing (aside from a few rare, exceptional circumstances), and the JIT message is produced in the Shown event.

Error info lost from worker thread

I would like to understand why the following behaviour happens and any ways to achieve what I need.
I have a main thread that spwans a backgorund worker to do some processing. I have a background worker completed even handler where I listen for any error. When there is an error I throw the error and allow it to float back to the main thread. I dont want to handle the error and show any message from the background worker.
But when the error is finally trapped in the main thread, I dont get to see the actual error message but I get an 'target invocation unknown' error. Would like to understand why and any ways to do such scenarios.
Comments:
Added Source Code Sample as requested.The reason why WCF was added because this logic is coded in a WCF service scenario. Hope it makes more sense now.
class ParentClass
{
static void main()
{
try
{
Thread t = new Thread(new ThreadStart(M1));
t.Start();
// ...
// ...
}
catch
{
// here I dont see the error as 'date time conversion'
// but see a generic error as I mentioned
}
}
static void M1()
{
try
{
Convert.ToDateTime("sss");
}
catch (Exception e)
{
// Here I see the error as 'error in date time conversion'
throw;
}
}
}
Thanks,
Mani
Without looking at code, it's hard to guess how you are passing the exception, but did you check the InnerException property of the Exception you receive. It may contain the information you are looking for. If there is no information, it could be that the code that is catching the exception and "floating" it may itself be generating an error.

Form Control getting disposed automatically shortly after form being created

I have this weird and inconsistent issue.
The application is built in compact framework 3.5 running on a windows mobile 6.5 device.
The screen flow of the application is somewhat like this.
MainScreen (which is always running)
Screen1
Screen2
Screen3
MainsScreen -> Screen1 -> Screen2 -> Screen3 -> MainScreen
When the loop is completed and the application lands back on MainScreen, MainScreen.Activated() is called and on a condition launches automatically Screen1.
The code looks something like this:
private void MainScreen_Activated(object sender, EventArgs e)
{
if (Condition)
{
NextScreen();
return;
}
//other code here
}
private void NextScreen()
{
Screen1 formScreen1 = new Screen1 ();
formScreen1 .Show();
}
Screen1 has also this piece of code in the load of the form:
private void Screen1_Load(object sender, System.EventArgs e)
{
if(Condition)
{
NextScreen();
}
}
private void NextScreen()
{
Screen2 formScreen2= new Screen2();
formScreen2.Show();
Close();
}
So when this condition in Screen1_Load is fulfilled the application automatically launches Screen2 and closes this.
In this particular case it happens that sometimes a control on Screen2 gets disposed after the form is created. I know this because i can actually see the control for a split second on the screen.
The issue is also inconsistent, it won't happen all the time in the exact scenario which makes me believe it's got to something with bad timing.
The control that gets disposed seems to be also chosen at random, most of the times it's the same button but there were cases when a listbox from the form got disposed.
Please note that there is no code in the application that will call dispose of the control.
Any help is greatly appreciated. Thank you, hope i explained the issue well enough.
I found the cause and a solution to my issue.
After much investigation i found out that the button being disposed was coinciding with this chance exception happening in debug:
A first chance exception of type 'System.ObjectDisposedException' occurred in System.Drawing.dll
A first chance exception of type 'System.ObjectDisposedException' occurred in System.Drawing.dll
I also found out that this chance exception can happen when the device is or thinks it's running out of memory causing the GC to run and try to clear memory.
I used the answer to this question
Prevent Garbage Collector and also added GC.KeepAlive on the form that were suffering this issue.
The chance exception still happens in debug at the same time but i haven't been able to reproduce the issue since then.

Categories

Resources