【发布时间】:2010-03-17 16:09:47
【问题描述】:
在MS Exam 70-536 .Net Foundation,第 1 课创建线程的第 7 章“线程”中有一段文字:
请注意,因为 WorkWithParameter 方法需要一个对象 Thread.Start 可以用任何对象而不是它期望的字符串来调用。谨慎选择 您的线程处理未知类型的启动方法对于良好至关重要 线程代码。而不是盲目地将方法参数转换为我们的字符串,而是 测试对象类型的更好做法,如下例所示:
' 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");
}
}
}
感谢您的宝贵时间!
【问题讨论】:
标签: .net multithreading exception-handling