读书人

线程等待的方法方法里的代码如何写啊

发布时间: 2012-01-16 23:36:52 作者: rapoo

线程等待的方法,方法里的代码怎么写啊?
线程等待的方法,方法里的代码怎么写啊?

[解决办法]
要写,

using System;
using System.Threading;

class ApartmentTest
{
static void Main()
{
Thread newThread =
new Thread(new ThreadStart(ThreadMethod));
newThread.SetApartmentState(ApartmentState.MTA);

// The following line is ignored since
// ApartmentState can only be set once.
newThread.SetApartmentState(ApartmentState.STA);

Console.WriteLine( "ThreadState: {0}, ApartmentState: {1} ",
newThread.ThreadState, newThread.ApartmentState);

newThread.Start();

// Wait for newThread to start and go to sleep.
Thread.Sleep(300);
try
{
// This causes an exception since newThread is sleeping.
newThread.SetApartmentState(ApartmentState.STA);
}
catch(ThreadStateException stateException)
{
Console.WriteLine( "\n{0} caught:\n " +
"Thread is not in the Unstarted or Running state. ",
stateException.GetType().Name);
Console.WriteLine( "ThreadState: {0}, ApartmentState: {1} ",
newThread.ThreadState, newThread.GetApartmentState());
}
}

static void ThreadMethod()
{
Thread.Sleep(1000);
}
}

读书人网 >C#

热点推荐