[英]Catching an exception thrown in a Thread
我需要知道在主應用程序中是否可以捕獲線程調用的方法內發生的異常。 我正在做Windows窗體應用程序,我要做的一件事情是在數據庫中存儲一些數據,但是如果由於某種原因操作不成功(例如,如果應用程序無法完成操作),我需要通知用戶連接到數據庫)。 問題是我必須調用該方法以將值從新線程插入數據庫中,因此,我從該方法內部使用try; catch塊。 但是,如果發生錯誤並且引發了異常,則沒有人能夠捕獲該異常,因此程序將崩潰。 我一直在做一些谷歌搜索,但我發現所有建議使用Task類而不是Thread,但是由於這是我大學的作業,因此我需要使用Threads。
那么,是否有辦法將異常從線程“轉移”到應用程序的主線程? 到目前為止,這是我的代碼:
//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
}
}
任何幫助或提示,我們將不勝感激。 謝謝!
我將使用這個非常有用的類: 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.