Set thread lifetime at startup

Is there a way to set the value of how long the thread should (maximize) be alive when the thread starts?

Speaking differently with "pseudo-code", there is something like this:

Thread t = new Thread(); t.start(); t.abort_after_x_seconds(30); 

due to which the stream is interrupted if it has lived for more than 30 seconds.

Edit: I still can't get it to work, which I originally had:

 while(true) { if(...) { Thread t = new Thread(new ThreadStart(startMethod)); t.start(); } Thread.sleep(...); } 

the problem is that sometimes the threads will hang (I do not implement what the threads do, so I don’t know exactly why (this is a school project, we are noobs when organizing)), so I want to kill these threads. I tried using Tasks and CancellationTokens, as in the examples below, but when the task hangs it cannot check if a cancellation request has occurred.

+6
source share
3 answers
  • In most cases, you should not use Thread s, use Task instead. They are more convenient and efficient.
  • Undoing something is unsafe; instead, you should use shared undo. If you call a method that supports cancellation, just pass it the cancellation token, which will be canceled after 30 seconds.

So your code might look like this (using .Net 4.5):

 var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30))); var task = Task.Run(() => YourMethod(cts.Token), cts.Token); 
+7
source

[EDIT: My answer was too slow. But I will leave it here for sample code.]

For this purpose you should use collaborative cancellation. The thread itself will need to determine when it should exit and respond accordingly.

There is a thing called CancellationToken created using a CancellationTokenSource that you can use for this purpose.

There is even a CancellationTokenSource constructor that allows you to set a timeout.

Here is a sample code to demonstrate its use:

 using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; namespace Demo { class Program { private void run() { using (var tokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(30))) { var task = Task.Run(() => exampleOne(tokenSource.Token)); task.Wait(); } using (var tokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(30))) { var task = Task.Run(() => exampleTwo(tokenSource.Token)); task.Wait(); } Console.WriteLine("Done."); } static void exampleZero() { Console.WriteLine("Starting exampleZero()"); try { Thread.Sleep(10000); // Simulate work. } catch (OperationCanceledException) { Console.WriteLine("Operation cancelled."); } Console.WriteLine("Exiting exampleZero()"); } static void exampleOne(CancellationToken cancellation) { Console.WriteLine("Starting exampleOne()"); // Busy loop processing. while (!cancellation.IsCancellationRequested) { // Do some work. } Console.WriteLine("Exiting exampleOne()"); } static void exampleTwo(CancellationToken cancellation) { Console.WriteLine("Starting exampleTwo()"); while (!cancellation.WaitHandle.WaitOne(100)) // Wait 100ms between work. { // Do some work. } Console.WriteLine("Exiting exampleTwo()"); } static void Main() { new Program().run(); } } } 
+1
source

Commentators note that using Abort is bad practice and an immediate interruption is not guaranteed. Why do you want to keep the stream alive? The thread will be returned to the pool when the task assigned to it is completed. The next time a task starts in a thread, it will be automatically transferred from the thread pool, either by creating another new one or by reusing the one available in the thread pool.

It seems like your logic / code is bad and needs to be fixed and not wait for something in x seconds and then complete it, which in itself will cause problems.

You may need a timer that can tick off after 30 seconds, then you can turn off the timer and kill the task at hand.

0
source

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


All Articles