内置后台调度系统.NET?后台、系统、NET

2023-09-03 05:52:51 作者:浪女

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

I ask though I doubt there is any such system.

基本上,我需要安排任务,在某些时候,在未来(通常不超过几秒钟或可能从现在分钟)执行,并有解除,除非太晚了请求某种方式。

Basically I need to schedule tasks to execute at some point in the future (usually no more than a few seconds or possibly minutes from now), and have some way of cancelling that request unless too late.

IE浏览器。 code,它是这样的:

Ie. code that would look like this:

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

有没有这样的系统在.NET?是否有TPL任何可以帮助我吗?

Is there any such system in .NET? Is there anything in TPL that can help me?

我需要在这里系统运行的各种情况下,这些未来的行动,宁可避免每一个这样的类的实例有它自己的线程和处理这个问题。

I need to run such future-actions from various instances in a system here, and would rather avoid each such class instance to have its own thread and deal with this.

另外请注意,我不希望这(或类似的,例如通过任务):

Also note that I don't want this (or similar, for instance through Tasks):

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

将有可能是一些这样的任务来执行,它们不需要以任何特定顺序执行,除了靠近其截止日期,并且它不是至关重要的,它们有一个像实时性能概念任何东西。我只是想避免旋转了一个单独的线程为每个这样的行动。

There will potentially be a few such tasks to execute, they don't need to be executed in any particular order, except for close to their deadline, and it isn't vital that they have anything like a realtime performance concept. I just want to avoid spinning up a separate thread for each such action.

推荐答案

既然你不希望有外部基准,你可能想看看的 System.Threading.Timer 或的 System.Timers.Timer的 。请注意,这些类在技术上是从的WinForms Timer组件有很大不同。

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.