C#关于线程的问题
1、通过System.threading.Thread类可以创建新的线程,并在线程堆栈中运行静态和动态的实例,可以通过Thread类的构造方法传递一个无参数,并且不返回的委托,
class Program
{
public static void myStaticThreadMethod(){
Console.WriteLine("myStaticThrteadMethod");
}
public void myThreadMethod() {
Console.WriteLine("myThreadMethod");
}
static void Main(string[] args)
{
Thread thread1 = new Thread(myStaticThreadMethod);
thread1.Start();//只有调用Start方法,线程才会启用
//Thread thread1 = new Thread(MyThread);
Thread thread2 = new Thread(new Program().myThreadMethod);
thread2.Start();
Thread thread3 = new Thread(delegate() { Console.WriteLine("niming weituo"); });
thread3.Start();
Thread thread4 = new Thread(() => { Console.WriteLine("Lambda biaodashi"); });
thread4.Start();
//Console.WriteLine("{0}", thread3.GetHashCode);
Console.ReadKey();
}
}
2、定义一个线程类
3、Thread 类有一个带参数的委托的重载形式,这个委托定义如下:
class
NewThread : MyThread
{
private
String p1;
private
int
p2;
public
NewThread(String p1,
int
p2)
{
this
.p1 = p1;
this
.p2 = p2;
}
override
public
void
run()
{
Console.WriteLine(p1);
Console.WriteLine(p2);
}
}
NewThread newThread =
new
NewThread(
"hello world"
,
4321
);
newThread.start();
{
static void Main(string[] args)
{
String i = "canshu";
Console.WriteLine("调用异步方法前");
PostAsync(i);
Console.WriteLine("调用异步方法后");
Console.ReadKey();
}
delegate void AsyncFoo(String i);
private static void PostAsync(object i) {
AsyncFoo caller = Myfucn;
caller.BeginInvoke(i.ToString(), FooCallBack, caller);
}
private static void FooCallBack(IAsyncResult ar) {
var caller = (AsyncFoo)ar.AsyncState;
caller.EndInvoke(ar);
}
private static void Myfucn(String i) {
Console.WriteLine("tonguo weituo shixian");
}
}