Set ApartmentState on a Task

前端 未结 6 803
轮回少年
轮回少年 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条回答
  •  佛祖请我去吃肉
    2020-11-27 03:08

    When StartNew fails you just do it yourself:

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

    (You can create one for Task that will look almost identical, or add overloads for some of the various options that StartNew has.)

提交回复
热议问题