-1

good morning am using C# to develop pc software and am using this method in my software to delay loop between lines

System.Threading.Thread.Sleep(x);

but this make my software freeze . how to do this method work with out freeze my application my full code

        private  void button18_Click_3(object sender, EventArgs e)
    {

        for (int i = 0; i < lstgroups.Items.Count; i++)
        {
            //
            System.Threading.Thread.Sleep(x);
            System.Windows.Forms.Application.EnableVisualStyles();
            //
            timeless.Enabled = true;
            timeless.Start();
            duration--;
            if (duration == 0)
            {
                timeless.Start();
            }

            if (Gsend.Post(lstgroupsbox.Items[i].ToString(), AppSettings.Default.AccessToken, txtStatus.Text, txtLink.Text) == true)
            lblshow.Text = "Sent To : " + lstgroups.Items[i].Text;
            lblsendid.Text = "Sent To : " + lstgroupsbox.Items[i];
            {
                //foreach (var item in lstgroups.Items)
                //{
                //    if (Gsend.Post(item.ToString(), "", txtStatus.Text, "", 2, "", txtImagePath.Text) == true)
                //        MessageBox.Show("Post Has Been Sent");
                //}

            }
Ahmed
  • 3
  • 5
  • Instead of Sleep, you should use timer. http://stackoverflow.com/questions/391621/compare-using-thread-sleep-and-timer-for-delayed-execution – Jitendra Pancholi Mar 17 '15 at 04:40

3 Answers3

1

Avoid using Thread.sleep() as it will put the Main thread on hold for given time and your GUI will freeze.

Other Option

  • Start Timer with interval you needed (X). and it should be fine.
  • Use background worker thread, as sleep in background worker will not effect your main GUI.
H. Mahida
  • 2,356
  • 1
  • 12
  • 23
  • 2
    Reference: http://stackoverflow.com/questions/391621/compare-using-thread-sleep-and-timer-for-delayed-execution :D – Jitendra Pancholi Mar 17 '15 at 04:44
  • its good method but give me this error This " BackgroundWorker is currently busy and cannot run multiple tasks concurrently. – Ahmed Mar 17 '15 at 09:42
0

Do the work on a thread that isn't the main thread. By using sleep in an event you are essentially halting any processing on the main thread.

Burrito
  • 517
  • 3
  • 8
0

Maybe you can use a Background Worker

Background Worker