Set ApartmentState on a Task

前端 未结 6 777
轮回少年
轮回少年 2020-11-27 03:02

I am trying to set the apartment state on a task but see no option in doing this. Is there a way to do this using a Task?

for (int i = 0; i < zom.Count; i         


        
6条回答
  •  萌比男神i
    2020-11-27 03:05

    This is what I'm using with Action since I don't need to return anything:

    public static class TaskUtil
    {
        public static Task StartSTATask(Action action)
        {
            var tcs = new TaskCompletionSource();
            var thread = new Thread(() =>
            {
                try
                {
                    action();
                    tcs.SetResult(new object());
                }
                catch (Exception e)
                {
                    tcs.SetException(e);
                }
            });
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            return tcs.Task;
        }
    }
    
    
    

    Where I call it like this:

    TaskUtil.StartSTATask(async () => await RefreshRecords());
    

    For details, please see https://github.com/xunit/xunit/issues/103 and Func vs. Action vs. Predicate

    FYI, this is the exception I was getting where I needed to set the apartment state:

    System.InvalidOperationException occurred HResult=-2146233079
    Message=The calling thread must be STA, because many UI components require this. Source=PresentationCore StackTrace: at System.Windows.Input.InputManager..ctor() at System.Windows.Input.InputManager.GetCurrentInputManagerImpl() at System.Windows.Input.Keyboard.ClearFocus()

    提交回复
    热议问题