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 - 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();
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.