0

如何在不阻塞 UI 线程的情况下轻松处理正在运行的任务中发生的所有异常。

我发现了很多不同的解决方案,但它们都涉及wait()功能,这会阻塞整个程序。

该任务正在异步运行,因此它应该只向 UI 线程发送一条消息,说明它有一个异常,以便 UI 线程可以处理它。(也许是我可以关注的事件?)

这是我现在拥有的阻止 UI 线程的代码:

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;
}
4

3 回答 3

2

你不应该使用Task.Factory.StartNewTask.Run改为使用)。另外,不要使用ContinueWithawait改为使用)。

应用这两个准则:

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
}
于 2016-10-18T15:32:25.733 回答
0

您可以订阅TaskScheduler.UnobservedTaskException活动

于 2016-10-18T14:52:09.653 回答
0

您使用的是 .Net 版本 4.5.2,因此您的语言版本应该是 c# 5。因此您可以执行以下操作:

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

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

await 关键字导致您必须使用异步标记您的方法。但它不会阻塞并且非常直观。如果这不起作用,请使用 Dmitry Bychenko 的想法:

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

      //Do you stuff which may cause exception
     }).ContinueWith(t=>ShowError(), TaskContinuationOptions.OnlyOnFaulted);
于 2016-10-18T14:56:23.660 回答