Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,855 questions

51,776 answers

573 users

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

1 answer 137 views
2 answers 197 views
197 views asked Jan 20, 2017 by avibootz
1 answer 146 views
1 answer 128 views
1 answer 153 views
1 answer 136 views
...