[英]Dynamically load and call delegates based on source data
假設我有一條記錄流,需要進行一些計算。 記錄有這些功能運行的組合Sum
, Aggregate
, Sum over the last 90 seconds
,或ignore
。
數據記錄如下所示:
Date;Data;ID
題
假設ID是某種int
類型,並且該int類型對應於要運行的某些委托的矩陣,那么我應該如何使用C#動態構建該啟動映射?
我確定這個想法存在...在Windows Forms中使用它,它具有許多委托/事件,其中大多數永遠不會在實際應用程序中實際調用。
下面的示例包括一些我要運行的代表(總和,計數和打印),但是我不知道如何根據源數據來激發代表數量。 (例如打印出偶數,然后求和該示例中的幾率)
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.