OK…
Looks like WinForms and Threading in the same program is something that I can’t master easily.
I’m trying to make a custom Numeric Up Down out of two picture boxes (used a buttons) and a text box. Yes, I can use the default NumericUpDown form, but I want to make a different looking one.
I have tried to do that with timers (System.Windows.Forms.Timer). The problem is that when one timer meets “Thread.Sleep(int)”, the whole program “falls to sleep”.
I tried with threads. Some types of threads can’t control the UI. Then I tried this
private void declare_thread()
{
//some work
Thread delay = new Thread(new ThreadStart(delay0));
delay.Start();
//some more work
}
//other functions
private void delay0()
{
//delay_for_500ms.WaitOne();
this.Invoke((ThreadStart)delegate()
{
Thread.Sleep(500);
if (is_mouse_down)
timer1.Enabled = true;
});
}
The result was the same as when I used timers only.
So, I want to make custom Numeric Up Down. But I can’t get it right. I know I’m doin’ it wrong. I want to make a thread that can control the UI and doesn’t make the whole program pause when calling “Thread.Sleep(int)”.
Please, give me answers for beginners. So far I haven’t found a good answer that can show me the right way and it’s easy to understand.
You’re looking for the wrong answer to the problem. There’s no such thing as a thread which can access UI controls and sleep without blocking the UI. Only the UI thread can access UI controls safely, and if you make the UI thread sleep, your UI will be unresponsive.
I’m afraid you need to bite the bullet and learn how to perform the threading properly. Note that sleeping is almost always the wrong approach – especially in the UI thread. You ahven’t really said what you’re trying to do, but a timer is a good way of saying, “I want to perform some action at a later point in time.” There are various different timers in .NET – which one you should use will depend on what you’re trying to do.
Threading is one of those topics that you can’t really shortcut – you should consider reading a thorough tutorial or a book which covers it in detail.