如何在不阻塞 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;
}