0

How can I easily handle all exceptions that happens inside the task that I am running without blocking the UI thread.

I found a lot of different solutions but they all involve the wait() function and this blocks the whole program.

The task is running async so it should just send a message to the UI thread saying that it has an exceptions so that the UI thread can handle it. (Maybe an event that I can hook on?)

This is the code I have now that blocks the UI Thread:

var task = Task.Factory.StartNew(() =>
{
    if (_proxy != null)
    {
        _gpsdService.SetProxy(_proxy.Address, _proxy.Port);
        if (_proxy.IsProxyAuthManual)
        {
            _gpsdService.SetProxyAuthentication(_proxy.Username,
                StringEncryption.DecryptString(_proxy.EncryptedPassword, _encryptionKey).ToString());
        }
    }

    _gpsdService.OnLocationChanged += GpsdServiceOnOnLocationChanged;
    _gpsdService.StartService();
});
try
{
    task.Wait();
}
catch (AggregateException ex)
{
    if (ex.InnerException != null)
    {
        throw ex.InnerException;
    }
    throw;
}
5
  • which c# version you are using? Is it possible for you to await the task? You need C# 5 for it. Then you can easily use a try catch Commented Oct 18, 2016 at 14:45
  • task.ContinueWith(task => {... }, TaskContinuationOptions.OnlyOnFaulted); Commented Oct 18, 2016 at 14:47
  • @Sebi We are using .NET version 4.5.2 right now. Commented Oct 18, 2016 at 14:48
  • @DmitryBychenko Can I actually throw the exception further up the three using this? because I want to throw It to the ViewModel that will actually handle the exception :) Commented Oct 18, 2016 at 14:51
  • @Ghosttje: looks like ViewModel should provide a routine for continuation (e.g. if any exception thrown It's a Model who should response for it): task.ContinueWith(task => SomeRoutine(task.Exception), TaskContinuationOptions.OnlyOnFaulted);. It doesn't look that easy as in sequential code. What if the model's run, say, 5 Tasks and 3d with 4th failed. Shall we throw 3d task's exception, or 4th one, comibine them (in which order)? Commented Oct 18, 2016 at 15:00

3 Answers 3

2

You should not use Task.Factory.StartNew (use Task.Run instead). Also, do not use ContinueWith (use await instead).

Applying both of these guidelines:

try
{
  await Task.Run(() =>
  {
    if (_proxy != null)
    {
      _gpsdService.SetProxy(_proxy.Address, _proxy.Port);
      if (_proxy.IsProxyAuthManual)
      {
        _gpsdService.SetProxyAuthentication(_proxy.Username,
            StringEncryption.DecryptString(_proxy.EncryptedPassword, _encryptionKey).ToString());
      }
    }

    _gpsdService.OnLocationChanged += GpsdServiceOnOnLocationChanged;
    _gpsdService.StartService();
  });
}
catch (Exception ex)
{
  // You're back on the UI thread here
  ... // handle exception
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can subscribe to the TaskScheduler.UnobservedTaskException event

Comments

0

You are using .Net version 4.5.2 so your languageversion should be c# 5. So you could be able todo the following:

try
{
 Task t1 = await Task.Factory.StartNew(() => {

  //Do you stuff which may cause exception
 })
}
catch ()
{}

The await keyword causes that you must mark your method with async. But it won't block and is very intuitive. If this don't work use the idea from Dmitry Bychenko:

Task t1 = await Task.Factory.StartNew(() => {

      //Do you stuff which may cause exception
     }).ContinueWith(t=>ShowError(), TaskContinuationOptions.OnlyOnFaulted);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.