Click here to Skip to main content
15,884,298 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
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??
C#
private void button1_Click(object sender, EventArgs e)
        {
            new Task(myFunction).Start();
        }
        private void myFunction()
        {
            Clipboard.SetText("this text will be copied to clipboard");
        }
Posted

C#
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();
        }
 
Share this answer
 
Comments
Vedat Ozan Oner 14-Feb-14 17:28pm    
ok, you can do it in that way. but I don't understand why someone wants to do this like that. are you testing something? and it would be better for you to write a tip about the subject instead of submitting a question, since you know the answer.
Asad Nawaz 14-Feb-14 18:05pm    
I researched a lot to for about 2 to 3 hours. After that I found the solution very hardly.
As There was a method in my application that requires large time to finish. when ever I call it in my form. My form was going to not responding mode.
Researched a lot about asynchronous functions calls, delegates etc.
Then some one told for Using Tasks. But my function uses Clipboard in it. So there was an exception.
I again searched and found the solution to call the function using this way.
Any Ways. Thank you so much Vedat OzanOner. You are the only, you tried to answer me ..
:-*
Thank you.
Sergey Alexandrovich Kryukov 14-Feb-14 19:56pm    
Asad,

Vedat is, in principle, right. Why asking a question and answering the same? You already knew the answer, so think: who else would be interested in that?
If you really have interesting findings (interesting for others), why not publishing some, say, Tips/Tricks article? Otherwise nothing is needed.

At the same time, your solution is relevant and can work. I doubt you really need to do so though. Please see my answer. But Vedat, while criticizing you, made much worse post. I have no idea why did you tell him that he "tried to answer". He did not. You solution at least can work; and you actually found advanced technique which is good to know... So, I have few more words to this member...

Vedat,

As you can see, I do understand your criticism, buy your own answer is a pure abuse. For anyone who would not know "real" solution but knowing the basics of programming, should be quite clear that your "answer" is a pure fake. If you handle some exception, it does not mean that failure you caught can turn into successful operation. Isn't that obvious? It it totally clear that you did not even try to consider the root cause of the problem. You totally ignored the real problem related to the apartment state. From your answer, we cannot learn anything about working with then, forget addressing the problem related to apartment states.

And what's worse, you actually set a very bad sample of using exception: handling them too locally. Actually, catching and handling exception at the level of a separate method is much worse then not taking care about it at all. Exceptions are designed to be isolated from "normal" instruction flow. They should only be handled at very few strategically selected points. I call them "points of confidence". Also, they should be caught in the main event loop of UI application and on the top stack frame of each stack. If you do what you show in your own work, this must be really bad work.

By your attempt to answer, you only make potential harm, nothing like help. When you answer (and when you criticize others), you should feel responsibility for your doing. It's way too easy to confuse some naive readers, beginners, and direct them in a wrong way.

Thank you for understanding.

—SA
Asad Nawaz 15-Feb-14 4:19am    
Hi Segery Alexandrovich Kryulov
you are right as If I know the answer I should post on tipes and trips. I got your point.
But I tried this way that I was unable to find the solution so I have posted my question.
But still researching other side.
After some hours, perhaps some one did't replied with working solution.
After doing research and research I found the solution. So I think it is a really Good Option in CodeProject.com to click "I Solved this My Self".
I never tried post a question for that I know the answer as I think this is really not good. For that I should definately post some article or tips and tricks for other. :)
Thank you Surgey Alexanfovich Kryunkov. You are really an intelligent and nice person. :)
Sergey Alexandrovich Kryukov 15-Feb-14 6:10am    
Thank you for your nice words.
Did you consider my answer and try to use this as a simpler option?
—SA
Instead of setting the apartment state of the separate thread (which is some cases makes perfect sense, because you may need to use one apartment state in one thread (say, main one) and different in some other thread, to use some API requiring certain apartment state), it doesn't look like you need it in your case.

Instead, you could simply set STA thread for your main thread at the point where you have your entry point method:
C#
using System;

//...

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

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
 
Share this answer
 
Comments
Asad Nawaz 15-Feb-14 4:27am    
Hi.
I tried this in my case "Windows Form Application."
But Main Function in Program.cs file Already contained.
[STAThread]
static void Main(/*...*/){
}
Even I tries to add [STAThread] to my every function in my program. But not worked. That's why I used the method I have mentioned in my answer.
Sergey Alexandrovich Kryukov 15-Feb-14 6:13am    
Really? Then let me ask you: do you have anything with MTAThread at all, anywhere? However, I have to check it up, maybe I forgot the defaults; it's easy to check up. Yes, your solution should work, I used to use this approach in opposite case, when MTAThread was required (speech recognition engine, for example; one of them).
—SA
use clipboard as in the following:

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


and take a look here for the thread mechanism. http://msdn.microsoft.com/en-us/library/windows/desktop/ms693344%28v=vs.85%29.aspx[^]
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 14-Feb-14 19:57pm    
Please see my comments to Solution 2, where I explain why this is nothing but fake answer and harmful advice.
—SA
Vedat Ozan Oner 15-Feb-14 6:21am    
please see the bottom of the page:

When answering a question please:

Read the question carefully.
Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.

Let's work to help developers, not make them feel stupid.
Sergey Alexandrovich Kryukov 15-Feb-14 6:33am    
Who makes stupid who? I don't feel too stupid if someone points out my mistakes, and even if I do, I do understand it was my problem, not the problem of the one who pointed out my mistakes.

You certainly can find places where other people find my mistakes. It happens. You won't find place where I "play the offended card" and counter-attack. You are picking quotation inadequate to the situation and try to set yourself beyond criticism.

—SA
Vedat Ozan Oner 15-Feb-14 6:41am    
then look at my comment in solution 2, again.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900