我写了一个多线程下载程序,
Thread t = new Thread(() =>
{
//功能处理
try
{
}
catch (Exception ex)
{
//这里处理异常
}我照上面的方法捕获了异常但是程序还是崩溃了。子线程运行中出现异常应该如何处理可以防止程序崩溃。
Thread t = new Thread(() =>
{
//功能处理
try
{
}
catch (Exception ex)
{
//这里处理异常
}我照上面的方法捕获了异常但是程序还是崩溃了。子线程运行中出现异常应该如何处理可以防止程序崩溃。
{
try
{
new System.Net.WebClient().DownloadFile(url, filepath);//下载文件
throw new Exception("多线程异常");
}
catch (Exception error)
{
MessageBox.Show("工作线程异常:" + error.Message + Environment.NewLine + error.StackTrace);
}
});
t.Start();
有的时候下载链接或者保存地址出错了就会导致程序崩溃。
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
} void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
}
看看异常
Thread t = new Thread(
() =>
{
//功能代码
Thread t1 = new Thread(
() =>
{
//功能代码
try
{
//出现异常
}
catch{//抛出异常}
t1.Start();
});
//如何在t中获取t1抛出的异常?
});
t.Start();
debug -> window -> thread
debug -> window -> thread
static void Main(string[] args)
{
Thread t = new Thread(() =>
{
//功能代码
Thread t1 = null;
t1 = new Thread(
() =>
{
//功能代码
try
{
//出现异常
throw new Exception("test");
}
catch
{
//抛出异常}
t1.Start();
}
});
//如何在t中获取t1抛出的异常?
});
t.Start(); Console.ReadKey();
}
{
//出现异常
throw new Exception("test");
}
根本就没有执行到。
你不信调试下。
你没有Start不会执行t1 = new Thread(() => {});里面的代码。
static void Main(string[] args)
{
Thread t = new Thread(() =>
{
//功能代码
Thread t1 = null;
t1 = new Thread(() =>
{
MessageBox.Show("Begin thread!");
//功能代码
try
{
//出现异常
throw new Exception("test");
}
catch
{
//抛出异常}
throw;
t1.Start();
}
});
//如何在t中获取t1抛出的异常?
t1.Start();
});
t.Start();
Application.ThreadException += (s, e) =>
{
MessageBox.Show(e.Exception.Message);
};
AppDomain.CurrentDomain.UnhandledException += (s, e) =>
{
MessageBox.Show(e.ExceptionObject.ToString());
};
Console.ReadKey();
}
可以拦截到,但是依然会退出的,楼上说的很对,自己线程中处理好。不要让别的线程给自己擦屁股。