c# - 如何从从委托集合中调用委托项目的父项运行子任务?
问题描述
我正在尝试从父级启动子任务,并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();
解决方案
因为 typeDelegate
没有指定任何函数签名,所以你需要使用一个实际的委托类型来Invoke
使用强类型。
考虑仅使用 1 个返回类型为object
(推荐使用)的委托类型,并在分配给此类委托时System.Func<object>
使用 like 包装函数。()=>MethodDS()
或者,如果您接受明显较低的性能,您可以简单地DynamicInvoke()
使用 week-type 调用,而不是Invoke()
for typeDelegate
推荐阅读
- java - Java 流有条件地添加多个值
- python - Python-使用两个列表计算平均数
- python - numpy - 为什么数值梯度 log(1-sigmoid(x)) 发散但 log(sigmoid(x)) 不发散?
- node.js - Strapi 中的 API 版本控制
- c# - 在 Delphi 中调用 .NET DLL 会导致访问冲突
- batch-file - 在 DosBox 中无法执行某些 DOS 命令
- python - Python如何隐藏代码
- android - Unity应用程序文本文件在Android Apk中显示问题
- java - 运行spring mvc-hibernate应用程序时出现异常
- node.js - TypeError:MongoStore 不是构造函数