Banshee
Banshee

Reputation: 15847

Handle Exceptions with tasks

Say that I have code like this:

serviceCallFinished = false;
Task.Factory.StartNew(() => {
    response = ServiceManager.GeneralService.ServiceMethod(loginName, password);
}).ContinueWith(parentTask => { serviceCallFinished = true; });

while (!serviceCallFinished)
    Thread.Sleep(100);

if (response.UserValid) { }

In this case the ServiceMethod will throw a Exception but this is never shown, instead I will get a null reference on the response.UserValid?

Why is the exception not handed over to my UI thread?

Note : This is on the UI thread and my idea is to not block the thread during the servicecall.

Upvotes: 3

Views: 444

Answers (4)

mehrandvd
mehrandvd

Reputation: 9116

Why don't you write code just like this:

Task.Factory.StartNew(() => 
  {
   response = ServiceManager.GeneralService.ServiceMethod(
     loginName, password);
  })
  .ContinueWith(parentTask => { if (response.UserValid) { } });

It seems more clear and more responsive.

Upvotes: 0

Marty Neal
Marty Neal

Reputation: 9563

From the comments and contrary to the example posted, it seems like you want logic that returns to the caller while a response is being awaited, and then do a bunch of stuff afterwards. It also sounds like the stuff afterwards contains a lot of very complex methods that you want to write procedurally. The C# team has heard your problem and many like it and developed the async/await framework that will do exactly that, slated for C# 5. Alternatively, if it is an option for you, there is an AsyncCTP available here: http://www.microsoft.com/download/en/details.aspx?id=9983 HTH.

Upvotes: 1

Joe
Joe

Reputation: 42666

You don't need to use a flag like that just to wait for an async task to finish. Use Wait()

Task t = Task.Factory.StartNew(() => {
    response = ServiceManager.GeneralService.ServiceMethod(loginName, password);
});

try
{
    t.Wait();
}
catch (AggregateException e)
{
   ...
}

the Wait() call will elevate any exceptions within an overall AggregateException.

Upvotes: 2

George Mamaladze
George Mamaladze

Reputation: 7931

Look at How to: Handle Exceptions Thrown by Tasks There is also a good sample.

Wha you could do is basically replace your sleeping loop with:

try
{
    task.Wait();
}
catch (AggregateException ae)
{
  ...
}

Upvotes: 0

Related Questions