[dba-VB] Threads and stuff

Shamil Salakhetdinov shamil at smsconsulting.spb.ru
Mon Oct 19 00:44:23 CDT 2009


<<<
Anyway, because the class method that 
the thread runs has to be static
>>>
Hi John,

Threads can run on instance methods - here is just a quick sample - no
static methods used at all except console app's entry method:

using System;
using System.Threading;
 
namespace ConsoleApplication1
{
    public class ThreadRunner
    {
        private int _threadNum;
        public ThreadRunner(int threadNum)
        {
            _threadNum = threadNum;
        }
        public void Run()
        {
            Console.WriteLine("{0:HH:mm.ss.fff}: Thread#{1} started, Id =
{2}",
                DateTime.Now,
                _threadNum,
                Thread.CurrentThread.ManagedThreadId); 
            
            Thread.Sleep(1100 - _threadNum*100 );

            Console.WriteLine("{0:HH:mm.ss.fff}: Thread#{1} finished.",
                DateTime.Now,
                _threadNum);
        }
    }

    public class ThreadManager
    {
        public void StartThreads()
        {
            for (int i = 1; i<=10; i++)
            {
               Thread th = new Thread(RunThread);
               th.Start(new ThreadRunner(i));  
            }
        }

        public void RunThread(object threadRunner)
        {
            ThreadRunner tr = (ThreadRunner)threadRunner;
            tr.Run(); 
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            (new ThreadManager()).StartThreads(); 
        }
    }
}

Here is output this sample produces:

09:41.53.519: Thread#3 started, Id = 5
09:41.53.519: Thread#1 started, Id = 3
09:41.53.522: Thread#4 started, Id = 6
09:41.53.524: Thread#5 started, Id = 7
09:41.53.520: Thread#2 started, Id = 4
09:41.53.524: Thread#6 started, Id = 8
09:41.53.524: Thread#7 started, Id = 9
09:41.53.524: Thread#8 started, Id = 10
09:41.53.524: Thread#9 started, Id = 11
09:41.53.524: Thread#10 started, Id = 12
09:41.53.625: Thread#10 finished.
09:41.53.724: Thread#9 finished.
09:41.53.824: Thread#8 finished.
09:41.53.924: Thread#7 finished.
09:41.54.024: Thread#6 finished.
09:41.54.124: Thread#5 finished.
09:41.54.223: Thread#4 finished.
09:41.54.323: Thread#3 finished.
09:41.54.424: Thread#2 finished.
09:41.54.523: Thread#1 finished.

--
Shamil


-----Original Message-----
From: dba-vb-bounces at databaseadvisors.com
[mailto:dba-vb-bounces at databaseadvisors.com] On Behalf Of jwcolby
Sent: Friday, October 16, 2009 10:27 PM
To: VBA
Subject: [dba-VB] Threads and stuff

....
Anyway, because the class method that the thread runs has to be static
...

-- 
John W. Colby
www.ColbyConsulting.com

 

__________ Information from ESET NOD32 Antivirus, version of virus signature
database 4520 (20091018) __________

The message was checked by ESET NOD32 Antivirus.

http://www.esetnod32.ru
 




More information about the dba-VB mailing list