好吧...请原谅我提出如此模糊的问题,但我因此而崩溃,我找不到一个好的逻辑来实现它,或者至少找不到一个好的库来为我做这样的事情。
情况
我的应用程序应该在不同的时间间隔内执行许多任务,其中一些任务仅在满足某些条件或其他方法完成等后才需要执行。 [将其视为方法依赖树] ...我想知道在像大型在线游戏或此类项目这样的大型项目中,他们如何组织代码以免在错误的时间或不在错误的时间崩溃或执行某些方法满足条件 ?
问题
整个问题是在我的应用程序中我需要以下规范
- 能够安排方法在指定时间运行。
- 能够暂停、取消、停止甚至重复一项任务。
- 能够在另一项任务完成之前不执行特定任务 这样我就可以创建某种流程。
- 能够创建某种流程以确保某些 方法永远不会执行,直到它的父方法或过程方法有 完成。
- 所有这些都以一种有条理、流畅而强大的方式进行。
最佳答案
Reactive Extensions (Rx.NET) 可以胜任! http://msdn.microsoft.com/en-us/data/gg577609.aspx
例子:
此示例安排任务执行。
Console.WriteLine("Current time: {0}", DateTime.Now);
// Start event 30 seconds from now.
IObservable<long> observable = Observable.Timer(TimeSpan.FromSeconds(30));
// Token for cancelation
CancellationTokenSource source = new CancellationTokenSource();
// Create task to execute.
Task task = new Task(() => Console.WriteLine("Action started at: {0}", DateTime.Now));
// Subscribe the obserable to the task on execution.
observable.Subscribe(x => task.Start(), source.Token);
// If you want to cancel the task do:
//source.Cancel();
Console.WriteLine("Press any key to exit");
Console.ReadKey();
结果:
示例 2:
每 x 秒重复一次任务。
Console.WriteLine("Current time: {0}", DateTime.Now);
// Repeat every 2 seconds.
IObservable<long> observable = Observable.Interval(TimeSpan.FromSeconds(2));
// Token for cancelation
CancellationTokenSource source = new CancellationTokenSource();
// Create task to execute.
Action action = (() => Console.WriteLine("Action started at: {0}", DateTime.Now));
// Subscribe the obserable to the task on execution.
observable.Subscribe(x => { Task task = new Task(action);task.Start(); },source.Token);
// If you want to cancel the task do:
//source.Cancel();
Console.WriteLine("Press any key to exit");
Console.ReadKey();
结果:
示例任务继续:
Console.WriteLine("Current time: {0}", DateTime.Now);
// Repeat every 2 seconds.
IObservable<long> observable = Observable.Interval(TimeSpan.FromSeconds(2));
// Token for cancelation
CancellationTokenSource source = new CancellationTokenSource();
// Create task to execute.
Action action = (() => Console.WriteLine("Action started at: {0}", DateTime.Now));
Action resumeAction = (() => Console.WriteLine("Second action started at {0}", DateTime.Now));
// Subscribe the obserable to the task on execution.
observable.Subscribe(x => { Task task = new Task(action); task.Start();
task.ContinueWith(c => resumeAction());
}, source.Token);
// If you want to cancel the task do:
//source.Cancel();
Console.WriteLine("Press any key to exit");
Console.ReadKey();
结果:
关于c# - 可靠的任务计划,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17889532/