如何将异常从任务/线程传播到在c#中创建此任务的方法?

时间:2016-04-12 09:29:43

标签: c# multithreading exception async-await task-parallel-library

我不知道如何将异常从Task传播到创建此任务的线程:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_reload: // Compile error: This item is not available
            // TODO reload
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

到达此行时:

ManagedPoolThread #98 10:03:56 ERROR Cannot send notifications for visitId: a425675d-2829-277b-300c-3882f33bb1c
Exception: System.ArgumentException
Message: The parameter 'address' cannot be an empty string.
Parameter name: address
Source: System
   at System.Net.Mail.MailAddress..ctor(String address, String displayName, Encoding displayNameEncoding)
   at Sitecore.Analytics.Rules.Actions.SendNotifications`1.SendMail(Subscription sessionSubscription, HtmlTextWriter output)
   at Sitecore.Analytics.Rules.Actions.SendNotifications`1.Apply(T ruleContext)

应用暂停说没有处理异常。 它可以传播回方法吗?

提前谢谢。

1 个答案:

答案 0 :(得分:1)

从线程池中执行的Task传播异常的最简单方法是将其转换为实际返回Task awaitpublic async Task AwaitOnTaskAsync() { try { await DoStuffWithThreadAsync(); } catch (Exception e) { } } public Task DoStuffWithThreadAsync() { return Task.Run(() => { throw new Exception("blabla"); }); }

await

Task将确保从try-catch中解包该异常,允许您在其上应用Task

附注 - 请勿使用Task.Run构造函数,而是使用Task返回&#34;热门任务&#34; (一个已经开始的)。在以后使用Thread.Sleep创建select A.Name, B.Surname, count(*), C.Pages from TableA Join TableB on A.Number = B.Number Join TableC on A.Number = C.Number group by A.Name, B.Surname, C.Pages; 时,无论是同步执行还是使用async-await来异步等待任务,都没有意义。< / p>