[英]Catching an exception thrown in a Thread
I need to know if an exception that happens inside a method called by a Thread can be catch in the main application. 我需要知道在主应用程序中是否可以捕获线程调用的方法内发生的异常。 I'm doing a Windows forms application and one of the things I have to do is store some data in a database, but I need to inform the user if, for some reason, the operation was unsuccessful (eg if the application couldn't connect to the database). 我正在做Windows窗体应用程序,我要做的一件事情是在数据库中存储一些数据,但是如果由于某种原因操作不成功(例如,如果应用程序无法完成操作),我需要通知用户连接到数据库)。 The thing is that I have to call the method to insert the values in the DB from a new Thread, and, therefore, I use the try;catch blocks from inside that method. 问题是我必须调用该方法以将值从新线程插入数据库中,因此,我从该方法内部使用try; catch块。 But if an error occur and the exception is thrown there is nobody able to catch it so the program crashes. 但是,如果发生错误并且引发了异常,则没有人能够捕获该异常,因此程序将崩溃。 I have been doing some google search but all that I could find recommended to use the class Task instead of Thread, but, because this is an assignment from my university, I need to use Threads. 我一直在做一些谷歌搜索,但我发现所有建议使用Task类而不是Thread,但是由于这是我大学的作业,因此我需要使用Threads。
So, is there a way to "transfer" the exception from a Thread to the main thread of the application ? 那么,是否有办法将异常从线程“转移”到应用程序的主线程? Here's my code so far: 到目前为止,这是我的代码:
//This is how I create the new Thread
public static Correo operator +(Correo c, Paquete p)
{
foreach (Paquete paq in c.Paquetes)
{
if (paq == p)
throw new TrackingIDRepetidoException("El paquete ya se encuentra cargado en la base de datos");
}
c.Paquetes.Add(p);
Thread hilo = new Thread(p.MockCicloDeVida);
hilo.Start();
c.mockPaquetes.Add(hilo);
return c;
}
public void MockCicloDeVida()
{
while (this.Estado != EEstado.Entregado)
{
Thread.Sleep(10000);
this.Estado += 1;
this.InformaEstado(this, new EventArgs());
}
try
{
// A simple method to insert an object in a DB. The try catch to check if the connection to the DB was succesfull or not is implemented here.
PaqueteDAO.Insertar(this);
}
catch (System.Data.SqlClient.SqlException e)
{
// I can't catch the exception here
}
}
Any help or tips is greatly appreciated. 任何帮助或提示,我们将不胜感激。 Thanks! 谢谢!
I would use this very useful class: TaskCompletionSource 我将使用这个非常有用的类: TaskCompletionSource
var tcs = new TaskCompletionSource<object>();
var th = new Thread(() => MockCicloDeVida(tcs));
th.Start();
try
{
var returnedObj = tcs.Task.Result;
}
catch(AggregateException aex)
{
Console.WriteLine(aex.InnerExceptions.First().Message);
}
public void MockCicloDeVida(TaskCompletionSource<object> tcs )
{
Thread.Sleep(10000);
tcs.TrySetException(new Exception("something bad happened"));
//tcs.TrySetResult(new SomeObject());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.