Set ApartmentState on a Task

前端 未结 6 807
轮回少年
轮回少年 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:06

    If Task needs to be provided with a CancellationToken, STA thread can be started within a task action and joined as shown below:

    var task = Task.Factory.StartNew(() =>
    {
        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();
        thread.Join();
    }, cancellationToken);
    
        

    提交回复
    热议问题