假设我有一个需要进行一些计算的记录流。记录将包含运行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));
}
}
答案 0 :(得分:0)
Dictionary<int, Func<int,int>> delegatesCache;
. . . (receive data here) . . .
var delToRun = delegatesCache[myData.Key];
var result = delToRun(myData.Param);