首页 > 解决方案 > 如何从从委托集合中调用委托项目的父项运行子任务?

问题描述

我正在尝试从父级启动子任务,并Invoke()从不同任务中的代表集合中委托。但是 VS 向我显示一个错误 - “委托不包含调用...”我如何运行此代码?

public struct DataStruct {...}
public class DataClass {...}

public class UserClass
{
          public delegate DataStruct UserDelegateDS();
          public delegate DataClass UserDelegateDC();

          public DataStruct MethodDS()
          {
               return new DataStruct();
          }
          public DataClass MethodDC()
          {
               return new DataClass();
          }
          public void Worker(List<Delegate> delegateCollection)
          {
               Task<object> parent = new Task<object>(() =>
               {
                    var results = new object [delegateCollection.Count];

                    for (int i = 0; i < results.Length; i++)
                    {
                         new Task(() => results[i] = delegateCollection[i].Invoke(), TaskCreationOptions.AttachedToParent).Start();
                    }

                    return results;
               });

               var cwt = parent.ContinueWith(pTask => Show(pTask.Result));
               parent.Start();
          }
          void ShowResults(object item) 
          {
               var items = item as object [];
               foreach(var t in items) {...}
          }
          public void Main()
          {
               List<Delegate> delegateCollection = new List<Delegate>();
               UserDelegateDS ds = MethodDS;
               UserDelegateDC dc = MethodDC;
               delegateCollection.Add(ds);
               delegateCollection.Add(dc);
               Worker(delegateCollection);
          }
}

Worker() 方法中的screen_from_VS问题:

new Task(() => results[i] = delegateCollection[i].Invoke(), TaskCreationOptions.AttachedToParent).Start();

标签: c#asynchronousdelegatestask

解决方案


因为 typeDelegate没有指定任何函数签名,所以你需要使用一个实际的委托类型来Invoke使用强类型。

考虑仅使用 1 个返回类型为object(推荐使用)的委托类型,并在分配给此类委托时System.Func<object>使用 like 包装函数。()=>MethodDS()

或者,如果您接受明显较低的性能,您可以简单地DynamicInvoke()使用 week-type 调用,而不是Invoke()for typeDelegate


推荐阅读