【发布时间】:2011-09-12 23:36:52
【问题描述】:
你好,是的,我第二次问这个问题,对此感到抱歉,但我不知道如何解决上一个问题。我将在更完整的示例中更深入地解释我的问题。
而不是在 300 个类文件中编写 300 多个事件类,如果这不起作用,我可能不得不这样做,所以他们可以在服务器项目中执行下面这个示例作业这样的少量定时作业。
我要避免的是编写一堆类,而只是将所有我正在处理的东西的结构更紧凑地写出来。
总而言之,我正在混合 90% 的函数式编程,并希望为某些函数提供一些延迟的定时事件,而不是在单独的类中创建新的定时事件,然后在文件中来回运行以查看所有内容是如何链接的up,但是这样可以看到所有内容,因此您可以更快地找到错误等等,因为所有内容都在您面前,有点像编写循环代码,但有延迟。
我现在只有一个线程来处理事件,删除已停止的事件,继续重新运行在一个周期后不会停止的事件,当然还要等到某些事件可以运行。
如果有人知道更好的方法来做我想做的事情,也许是一些内置的 C# 事件系统?最好是简单的。
class Event {
private Action action;
private bool stopped;
public Event(long tick, Action action) {
this.tick = tick;
this.action = action;
this.lastRun = Environment.TickCount;
}
public void stop() {
stopped = true;
}
public bool canRun() { //blah ignore just showing what I plan to do
if (stopped)
return false;
return (Environment.TickCount - lastRun) > tick;
}
public void run() {
this.lastRun = Environment.TickCount;
action();
}
//... other methods
}
class Test {
string t;
public void setT(string t) {
this.t = t;
}
public void stuff() {
Console.WriteLine(a);
}
}
class ImportantWork {
public static void Main(string[] args) {
someDeepMethod();
}
void someDeepMethod() {
Test t = new Test();
t.setT("secondTime");
//Here is where the problem occurs.
Server.registerEvent(new Event(5000, () => {
this.stop(); //<-- Error how I call this from this new Event instance.
stop(); //<-- Also error
//Event.stop(); //<-- haha may work if it was static but thats stupid
t.stuff();
Console.WriteLine("thirdTime");
}));
t.setT("firstTime");
t.stuff();
}
}
预期输出:
第一次
...等待 5 秒...
第二次
第三次
【问题讨论】:
-
当前上下文中不存在名称“stop”。 (删除它不会改变任何东西)
标签: c# visual-studio visual-studio-2010 lambda anonymous-methods