Casting TResult in Task to System.Object

后端 未结 3 1922
误落风尘
误落风尘 2020-12-16 01:54

I am loading an assembly and calling a static method that will create a new object of type “MyClass1” (this type is specified at runtime) through reflection using MethodInfo

3条回答
  •  心在旅途
    2020-12-16 02:14

    Another possibility is to write an extension method to this purpose:

        public static Task Convert(this Task task)
        {
            TaskCompletionSource res = new TaskCompletionSource();
    
            return task.ContinueWith(t =>
            {
                if (t.IsCanceled)
                {
                    res.TrySetCanceled();
                }
                else if (t.IsFaulted)
                {
                    res.TrySetException(t.Exception);
                }
                else
                {
                    res.TrySetResult(t.Result);
                }
                return res.Task;
            }
            , TaskContinuationOptions.ExecuteSynchronously).Unwrap();
        }
    
    
    

    It is none-blocking solution and will preserve original state/exception of the Task.

    提交回复
    热议问题