您的位置:首页 > 其它

在可以调用 OLE 之前,必须将当前线程设置为单线程单元(STA)模式

2008-12-02 12:17 411 查看
在可以调用 OLE 之前,必须将当前线程设置为单线程单元(STA)模式。请确保您的 Main 函数带有 STAThreadAttribute 标记。 只有将调试器附加到该进程才会引发此异常。

程序之前运行正常,我只是在一个事件中定义了做了如下操作,程序抛出此异常

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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐