gpt4 book ai didi

.net - MS 考试 70-536 - 如何从线程中抛出和处理异常?

转载 作者:行者123 更新时间:2023-12-01 05:04:57 26 4
gpt4 key购买 nike

MS Exam 70-536 .Net Foundation ,第1课Creating Threads中的Chapter 7“Threading”有一段文字:

Be aware that because the WorkWithParameter method takes an object, Thread.Start could be called with any object instead of the string it expects. Being careful in choosing your starting method for a thread to deal with unknown types is crucial to good threading code. Instead of blindly casting the method parameter into our string, it is a better practice to test the type of the object, as shown in the following example:

' VB
Dim info As String = o as String
If info Is Nothing Then
Throw InvalidProgramException("Parameter for thread must be a string")
End If
// C#
string info = o as string;
if (info == null)
{
throw InvalidProgramException("Parameter for thread must be a string");
}

所以,我试过了,但是异常处理不当(没有控制台异常条目,程序终止),我的代码有什么问题(如下)?

class Program
{
static void Main(string[] args)
{
Thread thread = new Thread(SomeWork);
try
{
thread.Start(null);
thread.Join();
}
catch (InvalidProgramException ex)
{
Console.WriteLine(ex.Message);
}
finally
{

Console.ReadKey();
}
}

private static void SomeWork(Object o)
{
String value = (String)o;
if (value == null)
{
throw new InvalidProgramException("Parameter for "+
"thread must be a string");
}
}
}

感谢您的宝贵时间!

最佳答案

Main 方法中的异常处理程序运行在与抛出异常不同的线程中。因此,thread 中的异常无法在Main 中捕获。检查here讨论为什么你不想跨线程抛出/捕获异常。你应该做的是使用一个对象来包装你的线程逻辑但支持异常。例如:

class Program
{
static void Main(string[] args)
{
ExceptionHandlingThreadWrapper wrapper = new ExceptionHandlingThreadWrapper();
Thread thread = new Thread(wrapper.Run);
try
{
thread.Start(null);
thread.Join();
if (wrapper.Exception != null)
throw new Exception("Caught exception", wrapper.Exception);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally { Console.ReadKey(); }
}
}

public class ExceptionHandlingThreadWrapper
{
public ExceptionHandlingThreadWrapper()
{
this.Exception = null;
}

public Exception Exception { get; set; }

public void Run(Object obj)
{
try
{
String value = obj as String;
if (value == null)
throw new Exception("Argument must be string");
}
catch (Exception ex)
{
this.Exception = ex;
}
}
}

关于.net - MS 考试 70-536 - 如何从线程中抛出和处理异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2463872/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com