//为线程传递参数
//为线程传递参数的最简单的方法莫过于执行一个lambda表达式,然后在方法里面给参数了
static void Main(string[] args)
{
Thread threadA = new Thread ( () => Print("Test") );
threadA.Start();
Console.ReadKey();
}
static void Print(string msg)
{
Console.Write(msg);
}
Lambda和捕获的变量。
for (int i = 0; i < 10; i++)
{
new Thread(() => Console.Write(i)).Start();
}
实际的输出是不确定的,例如可能是0113348899.
为什么???
关键的问题是局部变量i在for循环中指向的是相同的内存地址.因此,每一次都在一个运行时会被改变值的变量(i)上调用Console.Write方法,在foreach中也存在相同问题。
解决这个问题的方法很简单,例如使用一个临时的变量。例如:
for (int i = 0; i < 10; i++)
{
int temp = i;
new Thread(() => Console.Write(temp)).Start();
}
因为i是值类型,所以int temp=I 会复制i的值给temp,而在for循环中temp变量都是不同的,所以可以解决这个问题。
在“调试”菜单上指向“窗口”,再单击“线程”。 可以启用线程调试窗口
异常捕获:
尝试在一个线程中捕获另一个线程的异常时失败的。例如:
public static void Main()
{
try
{
new Thread(Go).Start();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message); //永远运行不到这里.
}
}
static void Go() { throw null;}
为了在另一个线程中捕获异常,必须在那个线程上try,catch,finally.
所以可以将代码改为下面的方式:
public static void Main()
{
new Thread(Go).Start();
}
static void Go()
{
try
{
throw null;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
//为线程传递参数的最简单的方法莫过于执行一个lambda表达式,然后在方法里面给参数了
static void Main(string[] args)
{
Thread threadA = new Thread ( () => Print("Test") );
threadA.Start();
Console.ReadKey();
}
static void Print(string msg)
{
Console.Write(msg);
}
Lambda和捕获的变量。
for (int i = 0; i < 10; i++)
{
new Thread(() => Console.Write(i)).Start();
}
实际的输出是不确定的,例如可能是0113348899.
为什么???
关键的问题是局部变量i在for循环中指向的是相同的内存地址.因此,每一次都在一个运行时会被改变值的变量(i)上调用Console.Write方法,在foreach中也存在相同问题。
解决这个问题的方法很简单,例如使用一个临时的变量。例如:
for (int i = 0; i < 10; i++)
{
int temp = i;
new Thread(() => Console.Write(temp)).Start();
}
因为i是值类型,所以int temp=I 会复制i的值给temp,而在for循环中temp变量都是不同的,所以可以解决这个问题。
在“调试”菜单上指向“窗口”,再单击“线程”。 可以启用线程调试窗口
异常捕获:
尝试在一个线程中捕获另一个线程的异常时失败的。例如:
public static void Main()
{
try
{
new Thread(Go).Start();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message); //永远运行不到这里.
}
}
static void Go() { throw null;}
为了在另一个线程中捕获异常,必须在那个线程上try,catch,finally.
所以可以将代码改为下面的方式:
public static void Main()
{
new Thread(Go).Start();
}
static void Go()
{
try
{
throw null;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
全局捕获异常:
为了捕获所有的未处理的异常,你可以使用AppDomain.CurrentDomain.UnhandledException
例子
static void Main(string[] args)
{
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
throw new Exception("test");
Console.ReadKey();
}
static void MyHandler(object sender, UnhandledExceptionEventArgs args)
{
Exception e = (Exception)args.ExceptionObject;
Console.WriteLine("Sender : "+sender.ToString()+" MyHandler caught : " + e.Message);
}