Embedded background planning in .NET?

I ask, although I doubt that there is such a system.

Basically, I need to plan tasks at some point in the future (usually no more than a few seconds or maybe minutes from this time), and have a way to cancel this request if it's too late.

Those. code that will look like this:

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

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

I need to run such future actions from different instances in the system here and rather avoid each such instance of the class in order to have my own thread and deal with it.

Also note that I do not want this (or similar, for example, through Tasks):

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

There may be several such tasks to perform, they do not need to be performed in any particular order, except for those close to their deadline, and it does not really matter that they have something like a real-time performance concept. I just want to avoid turning a separate thread for each such action.

+3
source share
6 answers

Since you do not want to have an external link, you can look at System.Threading.Timer or System.Timers.Timer . Note that these classes are technically very different from the Timer WinForms component.

+5
source

Use quartz.net (open source).

+3
source

Well ..... Actually, you can do exactly what you requested ....

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

Using the Rx Reactive Framework from our friends at Microsoft :)

Rx is pretty amazing. I just replaced events. It is just delicious ...

Hi, I'm rusty. I'm an Rx addict ... and I like it.

+3
source

Although not explicitly built into .NET, did you think you want to write EXEs that you can schedule through Windows Scheduled Tasks? If you use .NET, you are likely to use Windows, and isn't that what the intended tasks are for?

I don’t know how to integrate scheduled tasks into a .NET solution, but for sure you could write components called from scheduled tasks.

+1
source

If you want to use .NET 4, then the new System.Threading.Tasks provides a way to create custom schedulers for tasks. I did not study it too closely, but it looks like you could create your own scheduler and let it run tasks as you see fit.

+1
source

In addition to the answers provided, this can also be done using threadpool:

 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 has an Unregister method that can be used to cancel a request.

0
source

Source: https://habr.com/ru/post/1488296/


All Articles