3

I am trying to write an application which transfers data between 2 systems. This application is used by a user, so it is WinForm application. When data transfering is started by a click of the user, the GUI gets frozen even though I start the data transfering in another thread. I am doing something wrong but I couldnt figure it out. here is my SIMPLIFIED code below....

What am I doing wrong?

// Button Click Event
private void btnStart_Click(object sender, EventArgs e)
{
   StartThread();
}

// This starts the threaad.
public static void StartThread()
{
   string msg = string.Empty;
   int i = 0;

   continue_ = true;

   if (list != null)
   {
       while (continue_)
       {
           i++;
           Thread.Sleep(5000);

           Thread thrd1 = new System.Threading.Thread(() => Test());
           thrd1.Start();
       }
   }
}

// This is a simplified code.
public static void Test() 
{
        string msg = string.Empty;
        int i = 0;
        continue_ = true;
        while (continue_)
        {
            i++;
            Thread.Sleep(5000);
            FormMain.dal.ExecuteQuery("INSERT INTO A_TEST VALUES('"+i+"')",null,CommandType.Text,out msg);
        }
}
Arif YILMAZ
  • 5,754
  • 26
  • 104
  • 189

3 Answers3

2

Your StartThread() method includes a Thread.Sleep(5000) ... this is happening in your button click method, thus is making the UI thread sleep. Also, it looks like you have an infinite loop on the UI thread as continue_ never gets set to false

I'm guessing what you're trying to achieve here, but this may help:

public static void StartThread()
{
   Thread thrd1 = new System.Threading.Thread(() => Test());
   thrd1.Start();
}
Allan Elder
  • 4,052
  • 17
  • 19
0

Let's have a look at this block in StartThread:

while (continue_)
{
    i++;
    Thread.Sleep(5000);

    Thread thrd1 = new System.Threading.Thread(() => Test());
    thrd1.Start();
}
  1. You have a while loop dependen on continue_, but you never change it to false. So you get first of all an infinite loop, which causes the GUI to freeze.
  2. why you are modifying i, but never using it, so just remove it.
  3. You don't need also Thread.Sleep(5000);. However, if you really want to wait a time period, you can use an async delay. It will give the GUI free, so that the GUI works until the delay is finished. But for this, you have to declare StartThread as async.
Community
  • 1
  • 1
Maximilian Ast
  • 3,369
  • 12
  • 36
  • 47
-1

In your:

if (list != null)
{
   while (continue_)
   {
       i++;
       Thread.Sleep(5000);

       Thread thrd1 = new System.Threading.Thread(() => Test());
       thrd1.Start();
   }
}

You use Thread.Sleep(5000);

This however still targets your main thread. I would suggest you to remove this line.

Also, why do you use the variable 'i' while you never use it?

Dave
  • 434
  • 5
  • 22