向线程传递数据:
- 如果你想往线程的启动方法中传递参数,最简单的办法是使用lambda表达式,在里边使用参数调用方法。
- 在C#3.0之前没有lambda 表达式,可以使用Thread的Stat方法来传递参数。
For text One
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsolePlan
{
class Program
{
private const string MainThreadName = "MainThread";
static void Main(string[] args)
{
Thread.CurrentThread.Name = MainThreadName;
Program pr = new Program();
Thread thread = new Thread(() => Pro("bala bala bala...."));
thread.Name = "SubThread";
thread.Start();
Console.ReadKey(true);
}
static void Pro(string showStr)
{
Console.WriteLine(showStr);
}
}
}
For Text Two
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsolePlan
{
class Program
{
private const string MainThreadName = "MainThread";
static void Main(string[] args)
{
Thread.CurrentThread.Name = MainThreadName;
Program pr = new Program();
Thread thread = new Thread(Pro);
thread.Name = "SubThread";
thread.Start("la la la ....");
Console.ReadKey(true);
}
static void Pro(object showStr)
{
Console.WriteLine(showStr);
}
}
}
异常处理 try catch
- 创建线程时候在作用范围内的try/ catch ,在线程开始执行就与线程没有关系了,(人话就是线程间不能相互捕获异常,各自捕获各自的)
- 在WPF 和WinFrm中, 可以订阅全局异常处理实践。
- 如果想捕获全局异常可以注册事件:AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);在方法中处理异常机制问题
For Text
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;
namespace ConsolePlan
{
class Program
{
private const string MainThreadName = "MainThread";
private readonly static object lockObj = new object();
static void Main(string[] args)
{
Thread.CurrentThread.Name = MainThreadName;
Program pr = new Program();
Thread thread = new Thread(Pro);
thread.Name = "SubThread";
thread.Start("la la la ....");
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Console.ReadKey(true);
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
var exc = (Exception)e.ExceptionObject;
Debug.Print(exc.StackTrace + "\t" + exc.Message);
}
static void Pro(object showStr)
{
Console.WriteLine(showStr);
throw new Exception("Mesage Error!");
}
}
}