根据源数据动态加载和调用委托
本文关键字:调用 加载 动态 数据 | 更新日期: 2023-09-27 18:33:53
>假设我有一个需要一些计算的记录流。 记录将有这些函数的组合运行Sum
、Aggregate
、Sum over the last 90 seconds
或ignore
。
数据记录如下所示:
Date;Data;ID
问题
假设 ID 是某种int
,并且 int 对应于要运行的某些委托的矩阵,我应该如何使用 C# 动态构建该启动映射?
我敢肯定这个想法存在...它用于具有许多委托/事件的 Windows 窗体中,其中大多数永远不会在实际应用程序中实际调用。
下面的示例包括一些我想运行的委托(求和、计数和打印),但我不知道如何根据源数据触发委托的数量。 (假设打印偶数,并在此示例中对赔率求和)
using System;
using System.Threading;
using System.Collections.Generic;
internal static class TestThreadpool
{
delegate int TestDelegate(int parameter);
private static void Main()
{
try
{
// this approach works is void is returned.
//ThreadPool.QueueUserWorkItem(new WaitCallback(PrintOut), "Hello");
int c = 0;
int w = 0;
ThreadPool.GetMaxThreads(out w, out c);
bool rrr =ThreadPool.SetMinThreads(w, c);
Console.WriteLine(rrr);
// perhaps the above needs time to set up6
Thread.Sleep(1000);
DateTime ttt = DateTime.UtcNow;
TestDelegate d = new TestDelegate(PrintOut);
List<IAsyncResult> arDict = new List<IAsyncResult>();
int count = 1000000;
for (int i = 0; i < count; i++)
{
IAsyncResult ar = d.BeginInvoke(i, new AsyncCallback(Callback), d);
arDict.Add(ar);
}
for (int i = 0; i < count; i++)
{
int result = d.EndInvoke(arDict[i]);
}
// Give the callback time to execute - otherwise the app
// may terminate before it is called
//Thread.Sleep(1000);
var res = DateTime.UtcNow - ttt;
Console.WriteLine("Main program done----- Total time --> " + res.TotalMilliseconds);
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.ReadKey(true);
}
static int PrintOut(int parameter)
{
// Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " Delegate PRINTOUT waited and printed this:"+parameter);
var tmp = parameter * parameter;
return tmp;
}
static int Sum(int parameter)
{
Thread.Sleep(5000); // Pretend to do some math... maybe save a summary to disk on a separate thread
return parameter;
}
static int Count(int parameter)
{
Thread.Sleep(5000); // Pretend to do some math... maybe save a summary to disk on a separate thread
return parameter;
}
static void Callback(IAsyncResult ar)
{
TestDelegate d = (TestDelegate)ar.AsyncState;
//Console.WriteLine("Callback is delayed and returned") ;//d.EndInvoke(ar));
}
}
Dictionary<int, Func<int,int>> delegatesCache;
. . . (receive data here) . . .
var delToRun = delegatesCache[myData.Key];
var result = delToRun(myData.Param);