Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am still kind of new to C#, and especially threading in C#. I am trying to start a function that requires a single threaded apartment (STAThread)

But I am not able to compile the following code:

The function looks as follows in a separate class called MyClass:

internal static string DoX(string n, string p)
        {
            // does some work here that requires STAThread
        }

I have tried the attribute [STAThread] on top of the function but that does not work.

So I am trying to create a new Thread as follows:

 Thread t = new Thread(new ThreadStart(MyClass.DoX));

but this will not compile (The best overloaded method has invalid arguments error). However the example online is very similar (example here) What am I doing wrong and how can I simply make a function run in a new STA thread?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
418 views
Welcome To Ask or Share your Answers For Others

1 Answer

Thread thread = new Thread(() => MyClass.DoX("abc", "def"));
thread.SetApartmentState(ApartmentState.STA);
thread.Start();

If you need the value, you can "capture" that back into a variable, but note that the variable won't have the value until the end of the other thread:

int retVal = 0;
Thread thread = new Thread(() => {
    retVal = MyClass.DoX("abc", "def");
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();

or perhaps simpler:

Thread thread = new Thread(() => {
    int retVal = MyClass.DoX("abc", "def");
    // do something with retVal
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...