如何在不阻塞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;
}发布于 2016-10-18 23:32:26
您不应该使用Task.Factory.StartNew (改为使用Task.Run )。此外,请不要使用ContinueWith (改为使用await )。
应用这两个准则:
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-18 22:52:10
您可以订阅TaskScheduler.UnobservedTaskException事件
发布于 2016-10-18 22:56:24
您使用的是.Net版本4.5.2,因此您的语言版本应该是c# 5。因此,您可以执行以下操作:
try
{
Task t1 = await Task.Factory.StartNew(() => {
//Do you stuff which may cause exception
})
}
catch ()
{}await关键字导致您必须用async标记您的方法。但它不会阻塞,而且非常直观。如果这不起作用,可以使用Dmitry Bychenko的想法:
Task t1 = await Task.Factory.StartNew(() => {
//Do you stuff which may cause exception
}).ContinueWith(t=>ShowError(), TaskContinuationOptions.OnlyOnFaulted);https://stackoverflow.com/questions/40111090
复制相似问题