2011-03-23 6 views
3

이 주제와 관련하여 몇 가지 토론을 보았으며 가능하지 않다고 결론을 냈습니다. 쓰레드를 사용하고 STA로 만들어야하며 결과가 필요할 때 생성 된 쓰레드와 함께 메인 쓰레드에 참여하십시오. 이것은 작동하지만 대리자를 사용할 때 순수한 비동기 동작 (콜백 사용)을 얻을 수있는 이상적인 솔루션은 아닙니다. 그래서, 사각형을 만들기 위해서 - (Java에서와 같이) 자신의 Future 클래스를 구현하기 바로 전에; 위임자를 사용하여 더 좋은 방법이 있습니까?위임 스레드 STA를 만드는 방법


    private delegate String DelegateFoo(String[] input); 
    private String Foo(String[] input){ 
     // do something with input 
     // this code need to be STA 
     // below code throws exception .. that operation is invalid 
     // Thread.CurrentThread.SetApartmentState(ApartmentState.STA) 
     return "result"; 
    } 

    private void callBackFoo(IAsyncResult iar){ 
     AsyncResult result = (AsyncResult)iar; 
     DelegateFoo del = (DelegateFoo)result.AsyncDelegate; 
     String result = null; 
     try{ 
      result = del.EndInvoke(iar); 
     }catch(Exception e){ 
      return;   
     } 

     DelegateAfterFooCallBack callbackDel = new DelegateAfterFooCallBack (AfterFooCallBack); 
     // call code which should execute in the main UI thread. 
     if (someUIControl.InvokeRequired) 
     { // execute on the main thread. 
     callbackDel.Invoke(); 
     } 
     else 
     { 
     AfterFooCallBack(); 
     } 
    } 
    private void AfterFooCallBack(){ 
     // should execute in main UI thread to update state, controls and stuff 
    } 

답변

4

불가능합니다. 대리자의 BeginInvoke() 메서드는 항상 스레드 풀 스레드를 사용합니다. TP 스레드는 항상 MTA이므로 변경할 수 없습니다. STA 스레드를 얻으려면 스레드를 생성하고 스레드를 시작하기 전에 SetApartmentState() 메서드를 호출해야합니다. 이 스레드는 또한 Application.Run() 메시지 루프를 펌프해야합니다. COM 개체는 인스턴스에서 해당 스레드를 만들 때만 COM 개체를 사용합니다.

당신이 무엇을 하려는지는 확실치 않지만 스레드로부터 안전하지 않은 코드 덩어리를 멀티 스레드하려고하면 작동하지 않습니다. COM이이를 시행합니다.

+0

사실 Winform 응용 프로그램에서 Watin API에 액세스하려고합니다. Watin에 의해 노출 된 거의 모든 API는 STA에 있어야합니다. 내 메인 UI 스레드와 다른 스레드에서 IE 창을 열고 싶습니다. – karephul

+0

이 답변을 확인하십시오 : http://stackoverflow.com/questions/4269800/c-webbrowser-control-in-a-new-thread/4271581#4271581 –

+0

오 고마워 한스 !! 그게 거의 내가 뭘 찾고 있었는지 .. :) 그래서 스레드를 사용하여, 그것을 STA에 설정하고 그것을 순수 비동기 (콜백)로 만들 이벤트를 정의 .. C#을 바위 – karephul