none
Check for existing thread with parameters? RRS feed

  • Question

  • Hi All,

    I am fairly new to threading and trying to work out how to do something...

    I have a process I call as follows:

                        new Thread(new ThreadStart(race.ProcessRaceNow)).Start();


    And that all work fine, my problem is that I have this being called inside a timer that ticks over every second. Within the race.ProcessRaceNow method I set a flag in a database that would then stop the thread being called again under certain criteria, and that all works fine however it can take 5 or more seconds to set the flag in the database and in the meantime my thread has been launched another 5 or 6 times...

    How can I give the thread a name and then check for the existence of the thread before calling a new one? I only ever want to launch the thread once per race...

    Any help would be greatly appreciated.

    Cheers
    Dean

    Monday, May 28, 2012 7:45 AM

Answers

  • ohh Sorry Stewart Dannock

    Here the modified code..

     	Dictionary<string, Thread> myThreads = new Dictionary<string, Thread>();
    
            private void timer1_Tick(object sender, EventArgs e)
            {
                Thread th = null;
                if (myThreads.ContainsKey("yourRaceCode"))
                {
                    th = myThreads["yourRaceCode"];
                    if (th.ThreadState != ThreadState.Running)
                    {
                        th = new Thread(new ThreadStart(race.ProcessRaceNow));
                        th.Start();
                        myThreads["yourRaceCode"] = th;
                       
                    }
                }
                else
                {
                    th = new Thread(new ThreadStart(race.ProcessRaceNow));
                    th.Start();
                    myThreads.Add("yourRaceCode", th);
                   
                }
                
            }
    


    Sai Kumar K (MCP)
    Blog: Sai's Stuff.
    WebSite: SantoshTechnologies.

    Monday, May 28, 2012 10:22 AM

All replies

  • Hi Stewart Dannock,

    My first question is why to have another thread as Timer itself works on separate thread why can't you call ProcessRaceNow() method in Timer tick event handler method. 

    Any way this code may useful for you

    Declare a static thread variable @ class level like 

    static Thread th = null;

    Now place the following code in you timer tick event.

     	if (th!=null && !(th.ThreadState == ThreadState.Running))
            {
                th =  (new Thread(new ThreadStart(race.ProcessRaceNow))).Start();
            }
    Hope it Help you...



    Sai Kumar K (MCP)
    Blog: Sai's Stuff.
    WebSite: SantoshTechnologies.

    Monday, May 28, 2012 8:02 AM
  • Hi Sai,

    Thanks for your reply, what happens within the timer is that it selects race number from a database that start within the next 5 minutes and then launches the thread if it finds one. It's in a timer as it needs to check for races constantly.

    I like your idea except the problem is that I might have to start multiple instances of the thread based on different race codes so declaring the thread at class level would only allow me to process one race at a time wouldn't it?

    What I was hoping is that I could name each thread by the race code and then check if that race codes thread is still running then skip launching it again, does that make sense?

    Cheers
    Dean

    Monday, May 28, 2012 8:28 AM
  • Hi Stewart Dannock,

    I understand your requirement, for this use the same above code but instead of class level thread object declare it as Dictionary of Thread object and everytime you initiate a thread add the same to this dictionary with race code as the key and everytime you can retrieve and verify as the thread is still running or not.

    Hope this idea will workout for you...


    Sai Kumar K (MCP)
    Blog: Sai's Stuff.
    WebSite: SantoshTechnologies.

    Monday, May 28, 2012 8:40 AM
  • Hi Sai,

    Sorry if I sound a little ignorant here as I am still learning C# as well :)

    Would you be so kind as to give me a code example of how you would declare that?

    Regards,

    Dean

    Monday, May 28, 2012 9:00 AM
  • Hi Stewart Dannock,

    Here your complete code

    	Dictionary<string, Thread> myThreads = new Dictionary<string, Thread>();
    
            private void timer1_Tick(object sender, EventArgs e)
            {
                Thread th = null;
                if (myThreads.ContainsKey("yourRaceCode"))
                {
                    th = myThreads["yourRaceCode"];
                    if (th.ThreadState != ThreadState.Running)
                    {
                        th = (new Thread(new ThreadStart(race.ProcessRaceNow))).Start();
                        myThreads["yourRaceCode"] = th;
                    }
                }
                else
                {
                    th = (new Thread(new ThreadStart(race.ProcessRaceNow))).Start();
                    myThreads.Add("yourRaceCode",th);
                }
                
            }
    Hope this will help you... :)


    Sai Kumar K (MCP)
    Blog: Sai's Stuff.
    WebSite: SantoshTechnologies.

    Monday, May 28, 2012 9:10 AM
  • Sai,

    That's awesome! Thank you, you have taught me today that I still have so much to learn :)

    Cheers

    Dean

    Monday, May 28, 2012 9:35 AM
  • Welcome Stewart Dannock, if it is helped you can you mark it as Answer please :)

    Sai Kumar K (MCP)
    Blog: Sai's Stuff.
    WebSite: SantoshTechnologies.

    Monday, May 28, 2012 9:44 AM
  • I will, thanks...

    it is giving me an error though on this line th = (new Thread(new ThreadStart(race.ProcessRaceNow))).Start();

    Telling me "Cannot implicitly convert type 'void' to 'System.Threading.Thread'"?

    Monday, May 28, 2012 10:19 AM
  • ohh Sorry Stewart Dannock

    Here the modified code..

     	Dictionary<string, Thread> myThreads = new Dictionary<string, Thread>();
    
            private void timer1_Tick(object sender, EventArgs e)
            {
                Thread th = null;
                if (myThreads.ContainsKey("yourRaceCode"))
                {
                    th = myThreads["yourRaceCode"];
                    if (th.ThreadState != ThreadState.Running)
                    {
                        th = new Thread(new ThreadStart(race.ProcessRaceNow));
                        th.Start();
                        myThreads["yourRaceCode"] = th;
                       
                    }
                }
                else
                {
                    th = new Thread(new ThreadStart(race.ProcessRaceNow));
                    th.Start();
                    myThreads.Add("yourRaceCode", th);
                   
                }
                
            }
    


    Sai Kumar K (MCP)
    Blog: Sai's Stuff.
    WebSite: SantoshTechnologies.

    Monday, May 28, 2012 10:22 AM
  • Sai,

    I may have been a little hasty marking it as the answer :)

    It is still launching multiple threads for the same race code... 

    Here is my code:

       string raceDate = DateTime.Now.ToString("yyyyMMdd");
               string getRaceID = "select distinct RaceID, MeetingCode, RaceNum from LivePrices where RaceTime >= '" + DateTime.Now.ToString("HH:mm:00") + "' and RaceTime <= '" + DateTime.Now.AddMinutes(5).ToString("HH:mm:00") + "' and RaceDate =  '" + raceDate + "' and ISNULL(Status)";

                using (MySqlConnection con = new MySqlConnection("User ID=xxxxx; Password=xxxxx; Database=xxxxx; Data Source=xxxxx"))
                {
                    con.Open();
                    MySqlCommand rid = new MySqlCommand(getRaceID, con);
                    MySqlDataReader reader = rid.ExecuteReader(CommandBehavior.CloseConnection);
                    while (reader.Read())
                    {
                        string raceID = (string)reader["RaceID"];
                        ProcessRace race = new ProcessRace();
                        race._raceID = raceID;
                        race._MeetingCode = (string)reader["MeetingCode"];
                        race._BetEnabled = chkBet.Checked;
                        race._RaceNum = (int)reader["RaceNum"];
                        Thread th = null;
                        if (raceThreads.ContainsKey(raceID))
                        {
                            th = raceThreads[raceID];
                            if (th.ThreadState != ThreadState.Running)
                            {
                                th = new Thread(new ThreadStart(race.ProcessRaceNow));
                                th.Start();
                                raceThreads[raceID] = th;
                            }
                        }
                        else
                        {
                            th = new Thread(new ThreadStart(race.ProcessRaceNow));
                            th.Start();
                            raceThreads.Add(raceID, th);
                        }
                        Console.WriteLine("Thread Started for :" + raceID);
                    }
                }

    Monday, May 28, 2012 10:37 AM
  • Hi can you verify with all the enums in ThreadState @ line   

    if (th.ThreadState != ThreadState.Running)

    there is the really need to handle according to your requirement..

    Please let me know if you wont get.


    Sai Kumar K (MCP)
    Blog: Sai's Stuff.
    WebSite: SantoshTechnologies.

    Monday, May 28, 2012 10:41 AM
  • ah no, my mistake... it's where I placed the Console.WriteLine - Wrong place... it is actually working corectly and only starting 1 instance of each race :)

    Appreciate your help very much.

    Regards,

    Dean

    Monday, May 28, 2012 11:48 AM