MediaElement.CurrentState retrieves System.Exception - c#

I need to get the CurrentState from a MediaElement several times. I've created a simple function that looks like this:
private string getCurrentState(MediaElement m)
{
return m.CurrentState.ToString();
}
But everytime this function is called I get this:
An exception of type 'System.Exception' occurred in MyProject but was not handled in user code.
Additional information: The application called an interface that was marshalled for a different thread.
(Exception gfrom HRESULT: 0x8001010E (RCP_E_WRONG_THREAD))
I've been investigating about this issue and, as I've understood, it usually comes when trying to retrieve the CurrentState before the MediaOpenedevent's been fired. Actually, this not suits my case since this function is called after that. However I call the CurrentStateproperty I get the same exception and the weirdest thing of this all is that sometimes works, and sometimes not, so I definetely have got no idea of what is wrong in the code :S
Does anyone have any idea about how to fix it?

You are trying to get state from Non-ui thread. You should redesign you code to not interact with MediaElement from background thread (Task).
Or you can wrap getCurrentState method invocation into Despatcher
CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
<lambda for your code which should run on the UI thread>);

Related

'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?
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

Why does throw crash my program but return doesn't?

I am trying to catch exceptions for my form client not being able to establish a connection to a server with this in the Connect callback:
try
{
client.EndConnect(async);
}
catch (Exception e)
{
client.Close();
return;
}
This works fine but this behavior is encapsulated in to a class so I want to call throw; instead of return; so that the client class can handle it instead, like so:
try
{
client.Connect(host, port);
}
catch
{
Console.WriteLine("Could not connect to: " + host + ":" + port.ToString());
}
So why not just call throw; then? Well, for some reason if I call throw;, throw new Exception();, or basically anything other than return; the program failsfast. I'm really not sure what's causing this. I tried removing client.Close(); to see if it was the problem but nothing. If I don't call return; the program just immediately exits with no error.
Anyone know what's going on here?
Edit: I do not understand why I am getting downvoted so much. I showed how I am attempting to catch these exceptions and am asking why they are not working properly. I think the problem may be (not sure, just came up with this) because within the asynchronous callback, because it is a new thread in the ThreadPool, calling throw; does not do anything because, because it is not synchronous, there is nothing to throw back to and the application dies. Even with this knowledge, I am not sure how to solve this problem unless I put some sort of try-catch on the entire program.
I suppose a solution could be just sticking with return; because there is nothing to throw back to (due to the asynchronous callback nature of the method) and instead raise an event indicating a failure of connection. Regardless, many thanks for the downvotes and helping me solve this problem. Oh wait...
What's happening is that the EndConnect is not happening on the same thread as your BeginConnect. When EndConnect throws an exception, it is caught by the worker thread's unhandled exception handler, which fails fast (the other option is that it gets ignored and you never find out that your code isn't working).
You have to come up with a way to tell your main form thread that the connect failed.
As others have pointed out, you'll need to catch your exception one way or another to avoid program termination.
For some ideas on how you can do that "globally", see How to catch ALL exceptions/crashes in a .NET app. Whether this is actually a good idea depends on the specific needs of your program...
Relevant for WinForms:
Can't tell based on your question alone, but in case this is actually a WinForms application, you may need to be cognizant of the difference in behavior of modal forms that throw exceptions, depending on whether the debugger is active or not. Let's say we have two forms - the second one is shown as a modal child of the first one:
If application was started through debugger, second form is closed and and stack unwinding goes all the way to the first form's catch block (if any).
If application is started outside debugger, stack unwinding stops before second form is closed and generic exception message is displayed. The second form stays open and catch block in the first form is never reached.

Exception of type 'System.Windows.Forms.AxHost+InvalidActiveXStateException' was thrown

I am getting an error in my simple project.
This is my code:
if (axZKFPEngX1.InitEngine() == 0) {
label1.Text = "Connected";
}
else {
label1.Text = "Connection Failed";
}
I already added reference composites AxInterop.ZKFPEngXControl and Interop.ZKFPEngXControl.
While debugging, I click the button, and a warning appears:
InvalidActiveXStateException was handled.
"Exception of type 'System.Windows.Forms.AxHost+InvalidActiveXStateException' was thrown"**
try to call CreateControl() from your component first.
The answer by Constantin is Fulfill your requirement but here I wanted to add one more thing with it.
If you wanted to reflected this changes via all the threads and not only by calling thread (in multiple thread scenario) then use
CreateControl();
InitWB();
SkinAllThreads();
Actually in multiple threading scenario if your skinning code is in one of the thread then may be it is not reflect change for other current thread so at that time this code is play important role in it.
Here is some Documents I mention kindly go through it for reference :
initwb() method
DirectSkin other Methods
Adding Direct Skin to Application

How do I display an error message for a GUI app from non-GUI related classes?

I know I can use something like MessageBox.Show("some error") but I'm talking about an error that occurs at some lower level in my code that has no business tossing up a MessageBox or any other GUI elements.
I'm building an RSS Client and I have a class which manages the various feeds (lets say FeedManager) which is just a wrapper for a list at this point. Now this class calls on another class for data access. So anytime someone in the GUI wants to save the feeds, the GUI simply calls FeedManager.SaveFeeds() which processes the feeds and saves them to a file, database, etc. So I attempt to save to a file and something bad happens (either something I coded for or an exception). So now I'm at least 3 levels deep, GUI -> FeedManager -> SomeDataAccessLayer, and I want to display a message to the user like "Hey, that file was not found" or "You don't have permission to write to that location", etc...
How should I go about this? Throwing up a MessageBox from the data access layer blatantly couples that component to the GUI. Having all methods return strings with any error messages seems silly as well.
Non-GUI code should indeed not show a MessageBox.
The standard approach is to throw an Exception.
Your GUI should surround the call to SaveFiles() with a try/catch block and take the appropriate action, like showing a Messagebox.
Maybe you overlooked the point is that this is exactly what Exceptions are for: to communicate errors over (multiple) method calls.
Perhaps you could create a new class that handles errors, and that class will (depending on your wishes) print it to the console, display it in e.g. a public static GUI component, etc. That way you could decouple it from the GUI in an easy way, but still show messages in it
You should throw exception instead of message box
My solution for this was to use an event with a string parameter and whenever an exception (or any other error) occurred I triggered the event and past to it the message.
In the GUI class that create the instance just need to register to that event and in case it was triggered pop up a message box (or any other info).
namespace XXX {
public delegate void Error(string a_sErrorMessage);
public class XXX {
public event Error OnError;
public void Test() {
try {
// Do something
} catch (Exception ex) {
// Trigger the event
OnError(ex.Message);
}
}
}
}

top-level exception handling with event handlers in c#

I am currently asking myself some questions about exception handling and eventhandlers, and i hope some of you will give me some help.
I will start to explain what i would like to achieve in my c# application:
I have a top-level method (lets call it the main method). This method calls an asynchronous method (wich is called connect), which connect to a FTP server.
An EventHandler object is associated to this connection, and a "callback" method is called when the connection is successful.
I want to handle exceptions that can be launched during the whole process. So i would like to catch it in the top level method. It works fine for exceptions launched by the connect method (which is called inside the top level method).
However, it does not work for exceptions called inside the "callback" method: the top level method does not catch them and the execution fails.
What can I do to make these exceptions beeing caught by the top level method ? I don't want to handle these exceptions in the callback.
Take a look at how the Backgroundworker deals with this: the Exception is propagated to the Completed event handler.
I assume you have some form of State object that is passed to/from the delegate, that's where you can add such a property. And you will have to catch all exceptions in the thread, at the outermost scope. But 'handling' just means passing it along.
There is a standard pattern for the RunWorkerCompleted event, see this MSDN page.
Consider the below code fragment for wrapping all of your code in a global exception handler:
namespace MyClient
{
class Program
{
static void Main(string[] args)
{
try
{
bool isSuccess = SubMain(string[] args);
}
catch (Exception e)
{
HandleExceptionGracefully(e);
}
}
static bool SubMain(string[] agrs)
{
// Do something
}
static void HandleExceptionGracefully(Exception e)
{
// Display/Send the exception in a graceful manner to the user/admin.
}
}
}
Also, don't forget to make your error handling user-friendly.
There is an event handler in the Application class called ThreadException. This event will be fired whenever an exception is thrown an not caught anywhere in the current call stack.
Edited:
Sorry, I misread the question - I didn't realise that the "main" method in your example isn't the actual main method. In that case you may want to catch the exception inside the callback, but not handle it - instead simply pass it back up to the main method as part of the event args.
The BackgroundWorker in Winforms does something similar.
Thanks for your answers.
It seems that using the BackgroundWorker solve this problem.
I did not try it, because i chose to avoid this implementation burden. So I took away my asynchronous call and made my application behaving synchronously.
One tip for people using the Compact Framework instead of the full .NET Framework:
the BackgroundWorker is not available in CF, but a similar solution is provided by OpenNETCF (see the BackgroundWorker class in the Smart Device Framework).
A more convenient way to deal with this problem of top-level exception handling is to use delegates.
These c# delegates allow to call methods in a asynchronous way. And delegates allow also top-level exception handling. Indeed, exceptions thrown inside delegates are re-thrown on the original thread.
I don't know why i did not think about delegates before.
I hope it will help.
See these nice articles about delegates:
Article 1
Article 2

Categories

Resources