0

I am trying to start child tasks from parent and Invoke() delegate from collection of delegates in different tasks. But VS is showing me an error - "Delegate does not contain for Invoke..." How can i run this code?

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);
          }
}

problem screen_from_VS in Worker() method:

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

1 Answers1

1

Because type Delegate does not specify any function signature, you need to use an actual delegate type to Invoke with strong-type.

Consider using only 1 delegate type that has a return type of object (for which System.Func<object> is recommanded), and wrapping the functions with like ()=>MethodDS() when assigning to a delegate of such type.

Or if you accept significantly lower performance, you can simply call DynamicInvoke() with week-type, instead of Invoke() for type Delegate

Alsein
  • 4,268
  • 1
  • 15
  • 35