How to call a method with threading in C#

1 Answer

0 votes
using System;
using System.Threading;

namespace ConsoleApplication_C_Sharp
{
    public class myClass
    {
        public void Method()
        {
            while (true)
            {
                Console.WriteLine("myClass Method - run in thread");
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            myClass myclass = new myClass();

            Thread thread = new Thread(new ThreadStart(myclass.Method));

            thread.Start();

            // waiting for the thread to start
            while (!thread.IsAlive) ; 

            Thread.Sleep(2);

            thread.Abort();

            Console.WriteLine();
            Console.WriteLine("Thread finished");

            try
            {
                thread.Start();
            }
            catch (ThreadStateException ex)
            {
                Console.Write("Exception: {0}", ex.Message);
            }
        }
    }
}


/*
run:


myClass Method - run in thread
myClass Method - run in thread
myClass Method - run in thread
myClass Method - run in thread
myClass Method - run in thread
myClass Method - run in thread
myClass Method - run in thread
myClass Method - run in thread
myClass Method - run in thread
...

Thread finished

Exception: Thread is running or terminated; it cannot restart.

*/

 



answered Apr 28, 2017 by avibootz

Related questions

2 answers 218 views
218 views asked Jan 20, 2017 by avibootz
1 answer 154 views
1 answer 166 views
1 answer 150 views
1 answer 183 views
1 answer 155 views
...