programing

STA 스레드를 실행하는 태스크(TPL)를 작성하려면 어떻게 해야 합니까?

elecom 2023. 4. 23. 10:04
반응형

STA 스레드를 실행하는 태스크(TPL)를 작성하려면 어떻게 해야 합니까?

스레드 사용은 매우 간단합니다.

 Thread thread = new Thread(MethodWhichRequiresSTA);
 thread.SetApartmentState(ApartmentState.STA);  

WPF 어플리케이션에서 작업을 사용하여 동일한 작업을 수행하는 방법다음은 몇 가지 코드입니다.

Task.Factory.StartNew
  (
    () => 
    {return "some Text";}
  )
   .ContinueWith(r => AddControlsToGrid(r.Result));  

Invalid Operation을 받습니다.예외:

많은 UI 컴포넌트가 필요하기 때문에 호출 스레드는 STA여야 합니다.

TaskScheduler를 사용할 수 있습니다.From Current Synchronization Context 메서드: 현재 동기화 컨텍스트(WPF 응용 프로그램을 실행하는 경우 WPF 디스패처)의 Task Scheduler를 가져옵니다.

[ Continue ]를 사용합니다.TaskScheduler를 받아들이는 오버로드가 있는 경우:

var scheduler = TaskScheduler.FromCurrentSynchronizationContext();

Task.Factory.StartNew(...)
            .ContinueWith(r => AddControlsToGrid(r.Result), scheduler);

디스패처호출이 해결책이 될 수 있습니다.

    private async Task<bool> MyActionAsync()
    {
        // await for something, then return true or false
    }
    private void StaContinuation(Task<bool> t)
    {
        myCheckBox.IsChecked = t.Result;
    }
    private void MyCaller()
    {
        MyActionAsync().ContinueWith((t) => Dispatcher.Invoke(() => StaContinuation(t)));
    }

언급URL : https://stackoverflow.com/questions/5971686/how-to-create-a-task-tpl-running-a-sta-thread

반응형