我的问题有点类似这些问题:延迟方法调用使用委托
replay a list of functions and parameters
C# delegate for two methods with different parameters
我的目标是存储与它们在列表中的参数函数调用,调用他们一个不同的线程,由我的经理级别安排。
- 当函数被调用时,其自身添加到的记住参数的功能列表和值
- 当函数结束时,我想找回返回对象(如果有的话)
- 允许在功能列表中,以在以后的时间被称为
- 有不同的方法,用完全不同的签名 (他们中的一些有返回值(BOOL,INT,对象..),他们中的一些已经没有了,而的方法的参数数目是不固定的)
例如我想调用funstions那样:
ServerManager.addDoSomething(ServerManager.SERVICES.Login, serverURL, userName, password); // Login() with bool return type and 3 string parameters
ServerManager.addDoSomething(ServerManager.SERVICES.Query, searchExpr); // Query() with MyData return type and 1 string parameters
ServerManager.addDoSomething(ServerManager.SERVICES.Modify, searchExpr, newVal); // Modify() with int return type and 2 string parameters
ServerManager.addDoSomething(ServerManager.SERVICES.Logout); // Logout() with void return type and 0 parameters
或类似的:
ServerManager.addDoSomething(()=> ServerManager.SERVICES.Query (searchExpr));
ServerManager.addDoSomething(()=> ServerManager.SERVICES.Modify(searchExpr,的newval)); ServerManager.addDoSomething(()=> ServerManager.SERVICES.Logout()); ServerManager.addDoSomething(()=> ServerManager.SERVICES.Login(serverURL使用,用户名,密码));
或者什么支持接口其他方式..
应该怎样我ServerManager.addDoSomething方法(或者,如果签名不同的方法)变成什么样子,什么样的数据结构,我应该使用(WHAT_SHOULD_I_STORE),如果我想要支持延迟的函数调用..我怎样才能找回我的返回值?
我想,我不能让代表一般以这种方式,我可以用它来storeing具有不同签名的方法..
public static void addDoSomething(Delegate delegateParameter, string ...);
or
public static void addDoSomething(Func<...> methodToCall, string ...);
or
public static void addDoSomething(Action methodToCall, string ...);
or
public static void addDoSomething(delegate methodToCall, string ...);
我的课:
public class ServerManager
{
static List<WHAT_SHOULD_I_STORE> requestFIFO = new List<WHAT_SHOULD_I_STORE>();
public static IServerConnection SERVICES ;
static BackgroundWorker worker = new BackgroundWorker();
public ServerManager()
{
SERVICES = new ServerConnection();
worker.DoWork += (o, ea) =>
{
try
{
WHAT_SHOULD_I_STORE mr = null;
Application.Current.Dispatcher.Invoke(new Action(() => mr = popQueueElement()));
if (mr != null)
processRequestFromQueue(mr);
}
catch (Exception)
{
}
};
worker.RunWorkerCompleted += (o, ea) =>
{
worker.RunWorkerAsync();
};
if (! worker.IsBusy) worker.RunWorkerAsync();
}
private WHAT_SHOULD_I_STORE popQueueElement()
{
if (requestFIFO != null && requestFIFO.Count > 0)
{
WHAT_SHOULD_I_STORE result = requestFIFO.ElementAt(0);
requestFIFO.Remove(result);
return result;
}
else
return null;
}
private addDoSomething(...)
{
//....
}
}
public class ServerConnection : IServerConnection
{
// Concrete implementations of the IServerManager interface
}
public interface IServerConnection
{
bool Login (string serverURL, string userName, string password);
MyData Query (string serverURL, searchExpr);
int Modify (string searchExpr, string newVal);
void Logout ();
// ...
}
更新:我很抱歉,但我错过了名为“worker”的变量是BackgroundWorker类的一个实例.. – user1802693