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.

40,026 questions

51,982 answers

573 users

How to create thread in C#

1 Answer

0 votes
using System;
using System.Threading;

namespace ConsoleApplication1
{
    public class thread_test
    {
        public void func()
        {
            while (true)
            {
                Console.WriteLine("in func() function");
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                thread_test tt = new thread_test();

                // Create thread - func() running in its own thread - trd
                Thread trd = new Thread(new ThreadStart(tt.func)); 

                Console.WriteLine("trd Start");

                trd.Start();

                // waiting for thread to become alive
                while (!trd.IsAlive); // note the ;

                // Put the Main(string[] args) thread to sleep for 3 millisecond
                // In this time our trd start working
                Thread.Sleep(3);

                trd.Abort();

                // Wait until a thread terminates
                trd.Join();

                Console.WriteLine("trd end");

                // Aborted threads cannot be restarted - Exception
                trd.Start();
            }
            catch (ThreadStateException)
            {
                Console.WriteLine("Aborted threads cannot be restarted");
            }
        }
    }
}

/*
run:
     
trd Start
in func() function
in func() function
in func() function
in func() function
in func() function
in func() function
in func() function
in func() function
in func() function
in func() function
in func() function
in func() function
in func() function
in func() function
in func() function
in func() function
in func() function
in func() function
in func() function
in func() function
in func() function
in func() function
in func() function
in func() function
in func() function
in func() function
in func() function
in func() function
in func() function
in func() function
in func() function
in func() function
trd end
Aborted threads cannot be restarted
   
*/

 



answered Sep 8, 2015 by avibootz

Related questions

2 answers 105 views
2 answers 173 views
173 views asked Jan 20, 2017 by avibootz
1 answer 161 views
1 answer 155 views
1 answer 141 views
...