programing

호출 스레드는 STA여야 합니다. 많은 UI 구성 요소에서 이 작업이 필요하기 때문입니다.

instargram 2023. 5. 7. 10:57
반응형

호출 스레드는 STA여야 합니다. 많은 UI 구성 요소에서 이 작업이 필요하기 때문입니다.

저는 http://www.codeproject.com/KB/IP/Facebook_API.aspx 을 사용하고 있습니다.

WPF를 사용하여 생성된 XAML을 호출하려고 합니다.하지만 그것은 나에게 오류를 줍니다.

호출 스레드는 STA여야 합니다. 대부분의 UI 구성 요소에 STA가 필요합니다.

어떻게 해야 할지 모르겠어요.이 작업을 수행하려고 합니다.

FacebookApplication.FacebookFriendsList ffl = new FacebookFriendsList();

하지만 그것은 나에게 그 오류를 주고 있습니다.

백그라운드 작업자를 추가했습니다.

static BackgroundWorker bw = new BackgroundWorker();

static void Main(string[] args)
{
    bw.DoWork += bw_DoWork;
    bw.RunWorkerAsync("Message to worker");
    Console.ReadLine();
}

static void bw_DoWork(object sender, DoWorkEventArgs e)
{
    // This is called on the worker thread
    FacebookApplication.FacebookFriendsList ffl = new FacebookFriendsList();

    Console.WriteLine(e.Argument);        // Writes "Message to worker"

    // Perform time-consuming task...
}

디스패처에서 코드 호출 시도:

Application.Current.Dispatcher.Invoke((Action)delegate{
      // your code
});

주 스레드에서 호출하는 경우 이전 답변에서 설명한 대로 주 메서드에 STAT 스레드 속성을 추가해야 합니다.

별도의 스레드를 사용하는 경우 STA(싱글 스레드 아파트)에 있어야 하는데, 이는 백그라운드 작업자 스레드의 경우가 아닙니다.다음과 같이 스레드를 직접 만들어야 합니다.

Thread t = new Thread(ThreadProc);
t.SetApartmentState(ApartmentState.STA);

t.Start();

ThreadProc가 ThreadStart 유형의 대리인인 경우.

이것도 시도해 볼 수 있습니다.

// create a thread  
Thread newWindowThread = new Thread(new ThreadStart(() =>  
{  
    // create and show the window
    FaxImageLoad obj = new FaxImageLoad(destination);  
    obj.Show();  
    
    // start the Dispatcher processing  
    System.Windows.Threading.Dispatcher.Run();  
}));  

// set the apartment state  
newWindowThread.SetApartmentState(ApartmentState.STA);  

// make the thread a background thread  
newWindowThread.IsBackground = true;  

// start the thread  
newWindowThread.Start();  

백그라운드 스레드에서 UI 구성 요소에 대한 콜백을 받고 있는 것 같습니다.이 호출은 UI 스레드 인식이므로 BackgroundWorker를 사용하여 수행하는 것이 좋습니다.

BackgroundWorker의 경우 기본 프로그램이 [STAT 스레드]로 표시되어야 합니다.

를 을램프메메표하됩니소시다로 만 하면 .[STAThread]가 사라집니다입니다 :) ㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅠ

예:

class Program {
    [STAThread]
    static void Main(string[] args) {
    // My code here
    }
}

저의 경우, 콘솔 앱에서 WPF 창을 실행하고 싶었습니다.를 기인메 설정하로 .[STAThread]작동하지 않았습니다.

Timores와 Mohammad의 대답은 저에게 효과가 있었습니다.

private static void StaThreadWrapper(Action action)
{
    var t = new Thread(o =>
    {
        action();
        System.Windows.Threading.Dispatcher.Run();
    });
    t.SetApartmentState(ApartmentState.STA);
    t.Start();
}

사용 예:

StaThreadWrapper(() =>
{
    var mainWindow = new MainWindow();
    mainWindow.Show();
});

저는 null 매개 변수가 전달되었기 때문에 이 오류가 발생했습니다.변수 값을 확인한 결과 코드를 변경할 필요 없이 문제가 해결되었습니다.BackgroundWorker를 사용했습니다.

응용 프로그램인 경우.Current가 null입니다. 예를 들어 장치 테스트를 통해 다음을 시도할 수 있습니다.

 System.Windows.Threading.Dispatcher.CurrentDispatcher.Invoke( YOUR action )

새로운 선택하여 표시할 경우 다른 상황이 발생합니다.
App.xaml.cs 의 App()이나 OnStartup()에서 선택하지 말고 Startup 이벤트에서 선택하십시오.

// App.xaml.cs
        private App()
        {
            Window window = CheckSession() ? new InstallWindow() : (Window)new LoginWindow();
            window.Show(); // bad 1
        }

        protected override void OnStartup(StartupEventArgs e)
        {
            Window window = CheckSession() ? new InstallWindow() : (Window)new LoginWindow();
            window.Show(); // bad 2

            base.OnStartup(e);
        }

아래가 좋을 것입니다.

// App.xaml.cs
        private App()
        {
            Startup += Application_Startup;
        }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            Window window = CheckSession() ? new InstallWindow() : (Window)new LoginWindow();
            window.Show();  // good
        }

또한 App.xaml에서 StartupUri를 제거해야 합니다.

<!--App.xaml-->
<Application StartupUri="MainWindow">
<!--remove StartupUri-->
</Application>

또는 여기에 이벤트를 추가해도 괜찮습니다.

<!--App.xaml-->
<Application Startup="Application_Startup">

</Application>
// App.xaml.cs
        private App()
        {
            
        }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            Window window = CheckSession() ? new InstallWindow() : (Window)new LoginWindow();
            window.Show();  // good
        }

기존 스레드에서 새 창 UI 문을 호출하면 오류가 발생합니다.대신 주 스레드 내부에 새 스레드를 만들고 새 하위 스레드에 창 UI 문을 작성합니다.

언급URL : https://stackoverflow.com/questions/2329978/the-calling-thread-must-be-sta-because-many-ui-components-require-this

반응형