最近在做一个提示框,要用到线程,遇到的问题是不知道怎么在一个类中用同一个线程来调用所有方法。
后来想,是不是只要在线程中创建了这个类,那这个类里的所有原生的东西都属于这个线程。
于是写了个简单的程序试了下:
public class Class1
{
public void Method1()
{
Console.WriteLine("{0} - {1} - {2}",
"Class1",
"Method1",
Thread.CurrentThread.ManagedThreadId);
}
public void Method2()
{
Console.WriteLine("{0} - {1} - {2}",
"Class1",
"Method2",
Thread.CurrentThread.ManagedThreadId);
}
public void Method3()
{
Console.WriteLine("{0} - {1} - {2}",
"Class1",
"Method3",
Thread.CurrentThread.ManagedThreadId);
}
}
public class Class1Caller
{
public void CallClass1()
{
Task.Factory.StartNew(
delegate
{
Console.WriteLine("{0} - {1} - {2}",
"Class1Caller",
"CallClass1",
Thread.CurrentThread.ManagedThreadId);
Class1 c1 = new Class1();
c1.Method1();
c1.Method2();
c1.Method3();
});
}
}
public class Class2
{
public void CallClass2()
{
this.Method1();
this.Method2();
this.Method3();
}
private void Method1()
{
Task.Factory.StartNew(
delegate
{
Console.WriteLine("{0} - {1} - {2}",
"Class2",
"Method1",
Thread.CurrentThread.ManagedThreadId);
});
}
private void Method2()
{
Task.Factory.StartNew(
delegate
{
Console.WriteLine("{0} - {1} - {2}",
"Class2",
"Method2",
Thread.CurrentThread.ManagedThreadId);
});
}
private void Method3()
{
Task.Factory.StartNew(
delegate
{
Console.WriteLine("{0} - {1} - {2}",
"Class2",
"Method3",
Thread.CurrentThread.ManagedThreadId);
});
}
}
class Program
{
static void Main(string[] args)
{
Class1Caller c1c = new Class1Caller();
Class2 c2 = new Class2();
c1c.CallClass1();
c2.CallClass2();
Console.ReadLine();
}
}
测试结果:
证明我的设想是正确的。