I have a method that takes a callback argument to execute asynchronously, but the catch block doesn't seem to be catching any exceptions thrown by the synchronous call (this.Submit refers to a synchronous method).
public void Submit(FileInfo file, AnswerHandler callback)
{
SubmitFileDelegate submitDelegate = new SubmitFileDelegate(this.Submit);
submitDelegate.BeginInvoke(file, (IAsyncResult ar) =>
{
string result = submitDelegate.EndInvoke(ar);
callback(result);
}, null);
}
Is there a way to catch the exception thrown by the new thread and send it to the original thread? Also, is this the "proper" way to handle async exceptions? I wrote my code so it could be called like this (assuming the exception issue is fixed):
try
{
target.Submit(file, (response) =>
{
// do stuff
});
}
catch (Exception ex)
{
// catch stuff
}
but is there a more proper or elegant way to do this?
If you're targeting .NET 4.0, you can utilize the new Task Parallel Library, and observe the Task object's Exception property.
public Task Submit(FileInfo file)
{
return Task.Factory.StartNew(() => DoSomething(file));
}
private void DoSomething(FileInfo file)
{
throw new Exception();
}
Then use it like this:
Submit(myFileInfo).ContinueWith(task =>
{
// Check task.Exception for any exceptions.
// Do stuff with task.Result
});
where DoSomething is the method you'd like call asynchronously, and the delegate you pass to ContinueWith is your callback.
More information about exception handling in TPL can be found here: http://msdn.microsoft.com/en-us/library/dd997415.aspx
This is not a 'best practice' solution, but I think it's a simple one that should work.
Instead of having the delegate defined as
private delegate string SubmitFileDelegate(FileInfo file);
define it as
private delegate SubmitFileResult SubmitFileDelegate(FileInfo file);
and define the SubmitFileResult as follows:
public class SubmitFileResult
{
public string Result;
public Exception Exception;
}
Then, the method that actually does the file submission (not shown in the question) should be defined like this:
private static SubmitFileResult Submit(FileInfo file)
{
try
{
var submissionResult = ComplexSubmitFileMethod();
return new SubmitFileResult { Result = submissionResult };
}
catch (Exception ex)
{
return new SubmitFileResult {Exception = ex, Result = "ERROR"};
}
}
This way, you'll examine the result object, see if it has the Result or the Exception field set, and act accordingly.
In short, no.
When you call submitDelegate.BeginInvoke, it spawns the new thread, returns, and promptly exits your try/catch block (while the new thread runs in the background).
You could, however, catch all unhandled exceptions like this:
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(YourException);
This will catch everything in the application domain, however (not just your async method).
Related
The run() function in the following code is called from other threads simultaneously. At anytime, on any line, a ThreadAbortException might occur according to the general design of the application, which I cannot change.
I sometimes get SemaphoreFullException while calling pool.Release(). I think this occurs if a thread abort exception occurs while calling "pool.WaitOne()". During my debug tries, after SemaphoreFullException has occurred, there is no problem in running the code. After that exception, pool.WaitOne() calls and other things work just as expected.
I haven't been able to get a deadlock situation during my local debug sessions. However, in a remote computer, I have a deadlock with this code. I attach that process using remote debugger and see that the execution is locked on the line pool.WaitOne();.
I can't figure out how this would happen, and what I'm doing wrong. Any help is very appreciated.
private static object poolLocker = new object();
private static Semaphore _pool;
private static Semaphore pool
{
get
{
if (_pool == null)
lock (poolLocker)
if (_pool == null)
{
int count = myMaximumThreadCount;
_pool = new Semaphore(count, count);
}
return _pool;
}
}
private void run()
{
try
{
pool.WaitOne();
do_something_that_may_throw_exception();
}
finally
{
try
{
pool.Release();
}
catch (SemaphoreFullException) { }
}
}
Try to change the initialization of the semaphore object in pool property to:
private static Semaphore pool
{
get
{
if (_pool == null)
lock (poolLocker)
if (_pool == null)
{
int count = myMaximumThreadCount;
_pool = new Semaphore(0, count);
}
return _pool;
}
}
An initial count for this semaphore should be set to zero.
I have found the cause of the deadlock; and it has nothing to do with the question I've asked, so this is a bad question, sorry for that. There seems to be no problem in the code in the question.
The cause: In the do_something_that_may_throw_exception() function, an extern function of a C++ library is being called. When an error occurs in the C++ function, a SEHException is thrown. However, in my tries this exception can only be caught in a function that has HandleProcessCorruptedStateExceptions and SecurityCritical attributes. And that function happens to call the run() function of the question. However, the finally part of the run() function is newer executed! Also, if you have a using(IDisposable object){ ... } and the SEHException occurs inside it; object's Dispose() function won't be called.
I've used the following function for calling the C++ function; and everything worked fine:
SafeCall(()=> call_external_cpp_function());
[HandleProcessCorruptedStateExceptions]
[SecurityCritical]
internal static void SafeCall(Action action)
{
try
{
action();
}
catch (System.Threading.ThreadAbortException) { throw; }
catch (System.Threading.ThreadInterruptedException) { throw; }
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
I need to know if an exception that happens inside a method called by a Thread can be catch in the main application.
I'm doing a Windows forms application and one of the things I have to do is store some data in a database, but I need to inform the user if, for some reason, the operation was unsuccessful (e.g if the application couldn't connect to the database). The thing is that I have to call the method to insert the values in the DB from a new Thread, and, therefore, I use the try;catch blocks from inside that method. But if an error occur and the exception is thrown there is nobody able to catch it so the program crashes.
I have been doing some google search but all that I could find recommended to use the class Task instead of Thread, but, because this is an assignment from my university, I need to use Threads.
So, is there a way to "transfer" the exception from a Thread to the main thread of the application ? Here's my code so far:
//This is how I create the new Thread
public static Correo operator +(Correo c, Paquete p)
{
foreach (Paquete paq in c.Paquetes)
{
if (paq == p)
throw new TrackingIDRepetidoException("El paquete ya se encuentra cargado en la base de datos");
}
c.Paquetes.Add(p);
Thread hilo = new Thread(p.MockCicloDeVida);
hilo.Start();
c.mockPaquetes.Add(hilo);
return c;
}
public void MockCicloDeVida()
{
while (this.Estado != EEstado.Entregado)
{
Thread.Sleep(10000);
this.Estado += 1;
this.InformaEstado(this, new EventArgs());
}
try
{
// A simple method to insert an object in a DB. The try catch to check if the connection to the DB was succesfull or not is implemented here.
PaqueteDAO.Insertar(this);
}
catch (System.Data.SqlClient.SqlException e)
{
// I can't catch the exception here
}
}
Any help or tips is greatly appreciated. Thanks!
I would use this very useful class: TaskCompletionSource
var tcs = new TaskCompletionSource<object>();
var th = new Thread(() => MockCicloDeVida(tcs));
th.Start();
try
{
var returnedObj = tcs.Task.Result;
}
catch(AggregateException aex)
{
Console.WriteLine(aex.InnerExceptions.First().Message);
}
public void MockCicloDeVida(TaskCompletionSource<object> tcs )
{
Thread.Sleep(10000);
tcs.TrySetException(new Exception("something bad happened"));
//tcs.TrySetResult(new SomeObject());
}
I have a sync function such as the following function that generate an IO error (I delete the detail to make it simple):
public override void SyncFunction()
{
throw new IOException("test");
}
and I used it in this way:
try
{
await Task.Run(() => this.SyncFunction());
}
catch (Exception ex)
{
MessageBox.Show("Error:"+Environment.NewLine + ex.Message);
}
But when I run the application, the catch block doesn't get called, but I am getting a message that application crashed. What is the problem and how can I fix it?
The code as you described it should handle the exception just fine.
However, the thing that would crash your application is an exception thrown inside an async void method as the exception has no Task to be stored inside.
So, my guess is that SyncFunction actually looks more like this:
public override async void SyncFunction()
{
throw new IOException("test");
}
And when you invoke it the exception is posted to a ThreadPool thread and that crashes the application.
If that's the case, don't use async void unless in a UI event handler and make sure you handle such exceptions by registering to the AppDomain.CurrentDomain.UnhandledException event.
I have an anonymous TPL task with the following structure:
Task.Factory.StartNew(() =>
{
try
{
DoStuff();
}
catch (OperationCanceledException ex)
{
// process cancellation
}
catch (Exception ex)
{
// process (log) all exceptions
}
finally
{
// tie up various loose ends
}
},
myCancellationToken, // cancellation token
TaskCreationOptions.LongRunning, // always create a new thread
TaskScheduler.Default // default task scheduler
);
Inside of the DoStuff() function, I'm using Spring.NET Social extension for Dropbox to upload a large file to Dropbox. For some reason that I don't yet understand, an exception is being generating during the file upload (via the UploadFileAsync() method call):
(System.Net.Sockets.SocketException (0x80004005): An established connection was aborted by the software in your host machine).
I'm still working out why this exception is happening, but that's not the part that concerns me a present. The bigger problem is that the exception is ultimately wrapped by
System.Reflection.TargetInvocationException and for some strange reason, my try/catch block (in my original code snippet) isn't catching it.
Since I cannot catch the exception, it ultimately crashes the app.
Although I didn't think it should be necessary, I even tried adding an explicit catch block for TargetInvocationException, but again it never fires.
So my question is - how I do I catch this exception, and why isn't it being caught by the constructs shown in my code above?
UPDATE:
This problem appears to have nothing to do with the TPL after all. I modified the call to remove the call to StartNew() so that the code executes synchronously, and I still cannot catch this exception.
I used this code to verify that the TargetInvocationException can be caught:
[Test]
public void TaskExceptionTest()
{
var task = Task.Factory.StartNew(
() =>
{
try
{
throw new TargetInvocationException(null);
}
catch (Exception e)
{
Console.WriteLine("Caught one (inside):" + e.GetType().Name);
}
});
try
{
task.Wait();
}
catch (AggregateException ae)
{
// Assume we know what's going on with this particular exception.
// Rethrow anything else. AggregateException.Handle provides
// another way to express this. See later example.
foreach (var e in ae.InnerExceptions)
{
if (e is TargetInvocationException)
{
Console.WriteLine("After:" + e.GetType().Name);
}
else
{
throw;
}
}
}
}
You can read here about exception handling and tasks.
Whilst poking around some code using a .NET Reflector for an app I don't have the source code for, I found this:
if (DeleteDisks)
{
using (List<XenRef<VDI>>.Enumerator enumerator3 = list.GetEnumerator())
{
MethodInvoker invoker2 = null;
XenRef<VDI> vdiRef;
while (enumerator3.MoveNext())
{
vdiRef = enumerator3.Current;
if (invoker2 == null)
{
//
// Why do this?
//
invoker2 = delegate {
VDI.destroy(session, vdiRef.opaque_ref);
};
}
bestEffort(ref caught, invoker2);
}
}
}
if (caught != null)
{
throw caught;
}
private static void bestEffort(ref Exception caught, MethodInvoker func)
{
try
{
func();
}
catch (Exception exception)
{
log.Error(exception, exception);
if (caught == null)
{
caught = exception;
}
}
}
Why not call VDI.destroy() directly? Is this just a way of wrapping the same pattern of try { do something } catch { log error } if it's used a lot?
The reason appears to be to have a single function for handling and logging errors in operations that can fail: bestEffort. The delegate is used to wrap the action which can fail and pass it to the bestEffort function.
A delegate can be passed as an argument to a different function. The accepting function then does not have to know where that function is which class exposes it. It can invoke it and consume the results of it as it would from a regular method. The lambdas and then expression trees are built around delegates. Regular functions can't be evaluated at runtime which is possible with creating an expression tree with a delegate. You have you specific question answered already. So I will just add the general idea to the question.