3

我问虽然我怀疑有任何这样的系统。

基本上我需要安排任务在未来某个时间点执行(通常不超过几秒钟或几分钟后),并且有某种方式取消该请求,除非为时已晚。

IE。看起来像这样的代码:

var x = Scheduler.Schedule(() => SomethingSomething(), TimeSpan.FromSeconds(5));
...
x.Dispose(); // cancels the request

.NET 中有这样的系统吗?TPL 中有什么可以帮助我的吗?

我需要在这里从系统中的各种实例运行这样的未来动作,并且宁愿避免每个这样的类实例都有自己的线程并处理这个问题。

另请注意,我不想要这个(或类似的,例如通过任务):

new Thread(new ThreadStart(() =>
{
    Thread.Sleep(5000);
    SomethingSomething();
})).Start();

可能会有一些这样的任务要执行,它们不需要以任何特定的顺序执行,除非接近他们的截止日期,并且它们具有像实时性能概念这样的东西并不重要。我只是想避免为每个此类操作启动一个单独的线程。

4

6 回答 6

5

Since you don't want to have external reference, you might want to have a look at System.Threading.Timer, or System.Timers.Timer. Note that those classes are technically very different from the WinForms Timer component.

于 2010-06-02T13:36:40.337 回答
3

嗯......实际上你可以完全按照你的要求做......

  IDisposable kill = null;

  kill = Scheduler.TaskPool.Schedule(() => DoSomething(), dueTime);

  kill.Dispose();

使用我们在 Microsoft 的伙伴提供的 Rx反应式框架:)

Rx 是相当惊人的。我几乎用它替换了事件。它只是简单的美味......

嗨,我是 Rusty,我是 Rx 瘾君子……我喜欢它。

于 2010-06-05T21:36:20.127 回答
3

使用quartz.net(开源)。

于 2010-06-02T13:27:55.330 回答
1

While not explicitly built-in to .NET, have you considered writing EXEs that you can schedule via Windows Scheduled Tasks? If you're using .NET, you'll probably be using Windows, and isn't this exactly what Scheduled Tasks is for?

I'm not aware of how to integrate scheduled tasks into a .NET solution, but surely you could write components that get called from scheduled tasks.

于 2010-06-02T13:37:34.390 回答
1

如果您愿意使用 .NET 4,那么新的 System.Threading.Tasks 提供了一种为任务创建自定义调度程序的方法。我没有仔细研究它,但似乎您可以派生自己的调度程序并让它按照您认为合适的方式运行任务。

于 2010-06-05T22:05:59.340 回答
0

除了提供的答案之外,这也可以通过线程池完成:

public static RegisteredWaitHandle Schedule(Action action, TimeSpan dueTime)
{
    var handle = new ManualResetEvent(false);
    return ThreadPool.RegisterWaitForSingleObject(
                                         handle, 
                                         (s, t) =>
                                         {
                                             action();
                                             handle.Dispose();
                                         }, 
                                         null, 
                                         (int) dueTime.TotalMilliseconds, true);
}

RegisteredWaitHandle一个Unregister方法可以用来取消请求

于 2011-02-01T19:08:39.237 回答