0

I have a problem regarding the thread I have created. When I start the Thread, the CPU usage becomes higher and makes the server slow. I want to abort this process and re-run it. I am using a ClrThread to find the Method inside the processes using the namespaces. How can I do the Thread.Abort() in ClrThread?

this is my code.

        int _threadCounter = 0;
        Thread reminderThread = new Thread(CreateObject);
        string startOfThisNamespace = this.GetType().Namespace.ToString().Split('.')[0];
        using (DataTarget target = DataTarget.AttachToProcess(System.Diagnostics.Process.GetCurrentProcess().Id, false))
        {
            ClrRuntime runtime = target.ClrVersions.First().CreateRuntime();

            foreach(ClrThread _thread in runtime.Threads.ToList())
            {
                _threadCounter += 1;
                IEnumerable<ClrStackFrame> _stackFrames = _thread.EnumerateStackTrace();
                List<ClrStackFrame> _stackRelatedToUs = _stackFrames
                 .Where(o => o.Method != null && o.Method.ToString().StartsWith(startOfThisNamespace)).ToList();

                if (_stackRelatedToUs.Count > 0)
                {
                    foreach (var s in _stackRelatedToUs)
                    {
                        string _methodName = s.Method.Name;
                        if (_methodName == "CreateObject")
                        {
                            if (_thread.IsAlive)
                            {
                               //_thread.Abort(); Like This!!!
                            }
                        }
                        reminderThread.Start();                            
                    }
                }
                else
                {
                    if (_threadCounter == runtime.Threads.Count())
                    {
                       if (!reminderThread.IsAlive){
                          reminderThread.Start();                            
                       }
                    }
                }
            }
        }

Thank you and Regards.

Levesque Xylia
  • 349
  • 3
  • 16
  • 2
    How about you diagnose the actual problem you are having on that thread, a rude thread-abort is pretty dangerous as in most code it's completely unexpected and stuff may not unwind properly – Charlieface Apr 02 '21 at 03:44
  • Do you have code source control over the method that you are trying to abort? Because if you do, then you can modify it to take a CancellationToken and signal the method to kill itself at the appropriate time. – Rex Henderson Apr 02 '21 at 03:46
  • @RexHenderson, yes. Actually the method I am trying to call is the API i am working with. – Levesque Xylia Apr 02 '21 at 03:47
  • Then pass a CancellationToken into the method and have it monitor it while performing work. At least that way the method can have an opportunity to cleanly shutdown and exit – Rex Henderson Apr 02 '21 at 03:48
  • @RexHenderson , I will check that out. can you give me some hints to do that with the code above? if it's okay. that will be much appreciated. – Levesque Xylia Apr 02 '21 at 03:50
  • Sure, take a look at my answer – Rex Henderson Apr 02 '21 at 04:14
  • you might also read up on the Task class in System.Threading.Tasks. Using Task and the C# async/await features may offer you an alternative to using Threads directly – Rex Henderson Apr 02 '21 at 04:17
  • You don't abort any thread. You use cooperative cancellation. See duplicate. See also https://stackoverflow.com/questions/1559255/whats-wrong-with-using-thread-abort – Peter Duniho Apr 02 '21 at 06:20

1 Answers1

1

Here's a minor example for you

using System;
using System.Threading;

namespace ConsoleApp4
{
    class Program
    {



        static void Main(string[] args)
        {
            using (CancellationTokenSource source = new CancellationTokenSource())
            {
                CancellationToken token = source.Token;

                token.Register(Notify);
                
                new Thread(Worker).Start(token);

                Console.WriteLine("Press a key to abort the thread");
                Console.ReadLine();

                source.Cancel();
                
                //wait 5 seconds for the thread to abort
                source.Token.WaitHandle.WaitOne(5000, true);
            }
            
        }

        /// <summary>
        /// callback to do stuff when thread is cancelled
        /// </summary>
        static void Notify()
        {
            Console.WriteLine("thread is cancelled");
        }

        /// <summary>
        /// worker thread
        /// </summary>
        /// <param name="token"></param>
        static void Worker(object token)
        {
            CancellationToken _token = (CancellationToken)token;

            do
            {
                Console.WriteLine("thread is working....");
                Thread.Sleep(1000); //pretend I'm doing work
            } while (!_token.IsCancellationRequested);
        }

    }
}
Rex Henderson
  • 412
  • 2
  • 7