本文介绍了在ClipBoard.SetText()函数中无法处理ThreadStateException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HI。

当我点击按钮并运行以下代码时,我无法解决异常。

ThreadStateException未被用户代码处理

在进行OLE调用之前,必须将当前线程设置为单线程单元(STA)模式。确保主函数上标有STAThreadAttribute。



任何人都有这个想法吗?

HI.
When I click the button and run the following code I am unable to resolve the exception.
ThreadStateException was unhandled by user code
"Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it."

Any one has the idea??

private void button1_Click(object sender, EventArgs e)
        {
            new Task(myFunction).Start();
        }
        private void myFunction()
        {
            Clipboard.SetText("this text will be copied to clipboard");
        }

推荐答案

private void button1_Click(object sender, EventArgs e)
        {
            new Task(myFunction).Start();
        }
private void myFunction()
        {
           RunAsSTAThread(
            () =>
            {
                ClClipboard.SetText("this text will be copied to clipboard");
            });
            
        }

static void RunAsSTAThread(Action goForIt)
        {
            AutoResetEvent @event = new AutoResetEvent(false);
            Thread thread = new Thread(
                () =>
                {
                    goForIt();
                    @event.Set();
                });
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            @event.WaitOne();
        }


using System;

//...

[STAThread]
static void Main( /* ... */  ) {
    //...
}



这种方式可能看起来不够通用。它不是。它适合大多数情况。让我们看看:控制台应用程序可以以 STAThread MTAThread 开头,与系统相同.Windows.Forms ,但WPF需要 [STAThread] 。换句话说,在大多数情况下, STAThread 不会出错。只有在某些特殊情况下你才需要两者。



-SA


This way may look not universal enough. It is not. It's just fit most of the cases. Let's see: a console application can start with either STAThread or MTAThread, same thing with System.Windows.Forms, but WPF requires [STAThread]. In other words, in most cases, you cannot go wrong with STAThread. And only in some special cases you many need both.

—SA


private void button1_Click(object sender, EventArgs e)
        {
            // new Task(myFunction).Start();
            try
            {
                myFunction();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }





并在这里查看线程机制。 []


这篇关于在ClipBoard.SetText()函数中无法处理ThreadStateException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 10:25