In MS Exam 70-536 .Net Foundation, Chapter 7 “Threading” in Lesson 1 Creating Threads there is a text:
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");
}
So, I’ve tried this but exception is not handled properly (no console exception entry, program is terminated), what is wrong with my code (below)?
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");
}
}
}
Thanks for your time!
First start in VS in debug mode. Now to code, several issues:
will never be executed because exception is local to thread. If you throw exception in spawned thread other threads will not see it.
this line causes unhandled exception, because in that thread no one caught it. unhandled exception fail entire app.
o can be null which is valid value for String and your code will throw exceptions if o is not string. Did you meant: