How to run something in the STA thread?

后端 未结 5 1292
礼貌的吻别
礼貌的吻别 2020-11-29 03:17

In my WPF application I do some async communication (with server). In the callback function I end up creating InkPresenter objects from the result from server. This requires

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 04:11

    It's a bit of a hack, but I would use XTATestRunner So your code will look like:

        public void SearchForFooAsync(string searchString)
        {
            var caller = new Func(_patientProxy.SearchForFoo);
            caller.BeginInvoke(searchString, new AsyncCallback(SearchForFooCallbackMethod), null);
        }
    
        public void SearchForFooCallbackMethod(IAsyncResult ar)
        {
            var foo = GetFooFromAsyncResult(ar); 
            InkPresenter inkPresenter;
            new XTATestRunner().RunSTA(() => {
                inkPresenter = XamlReader.Parse(foo.Xaml) as InkPresenter;
            });
        }
    

    as a bonus it's possible to catch exceptions thrown in STA (or MTA) thread like this:

    try
    {
        new XTATestRunner().RunSTA(() => {
            throw new InvalidOperationException();
        });
    }
    catch (InvalidOperationException ex)
    {
    }
    

提交回复
热议问题