Starting an STAThread in C#

后端 未结 1 1927
心在旅途
心在旅途 2020-12-05 10:25

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

相关标签:
1条回答
  • 2020-12-05 10:56
    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();
    
    0 讨论(0)
提交回复
热议问题