Home > Back-end >  What is the right way to abort a method that will never complete C# - Without Thread.Abort
What is the right way to abort a method that will never complete C# - Without Thread.Abort

Time:04-08

Since the Thread.Abort method is not supported by Microsoft anymore. What is the correct way to get past an operation that is never (or within specified time) expected to complete. The code with Thread.Abort that I have written is below:

try
        {
            CancellationTokenSource cts = new CancellationTokenSource();                
            Task t = Task.Run(() =>
            {
                TClass c1 = new TClass();

                using (cts.Token.Register(Thread.CurrentThread.Abort))
                {
                    c1.Generate();
                }
            }, cts.Token);
            TimeSpan ts = TimeSpan.FromSeconds(5);
            if (!t.Wait(ts))
            {
                cts.Cancel();                  
                throw new Exception("Test success");
            }
        }
        catch (Exception e)
        {                
            Console.WriteLine(e.Message);                             
        }  
}

Note: c1.Generate() represents a method that we wish to abort if it does not complete within specific time.

Reference: https://docs.microsoft.com/en-us/dotnet/api/system.threading.thread.abort?view=net-6.0

Edit:

Added code for TClass:

public class TClass:IDisposable
{
    public Thread Thread { get { return Thread.CurrentThread; } }
    public TClass()
    {

    }

    public void Dispose()
    {
        GC.SuppressFinalize(this);
    }

    public void Generate()
    {
        int x = 0;
        while (true)
        {
            Console.WriteLine(x  );
            Task.Delay(TimeSpan.FromSeconds(1)).Wait();
        }
    }
}

CodePudding user response:

The right way to abort a non-cancelable method that will never complete, is to run this method on a separate process, and then cancel it by killing the process. Hopefully this method has no return value, because otherwise you will have to get this value through inter-process communication, which is not trivial.

Another possible solution that is not guaranteed to work, is to use the Thread.Interrupt method. This only works if you know the thread on which the method is running, and that thread transitions periodically (or permanently) to a sleeping state. Some operations, like asynchronous methods, are not running on threads, so it's not guaranteed that the operation will terminate, even if you kill the thread that started this operation by interrupting it.

CodePudding user response:

The recommended way (especially for ASP.NET Core) is now to use Tasks and "abort" them with CancellationTokens. You can learn more about how to use CancellationTokens here.

  • Related