Don't use DoEvents(). Use threads!
That mantra is roaming around the internet including SO. Okey so I created a short proof of concept where I tried to use only Threads. So basically what button should do is trigger moving the blue box downwards.
It runs in a separate thread YET windows form is unresponsive (I can't move it or click the button again) until it finishes moving downwards.
Question is, what did I mess up? If I shouldn't use DoEvents(), what instead? (If you uncomment the Application.DoEvents()
line, it'll become responsive).
CODE
using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
namespace doevents
{
public partial class Main : Form
{
// Use static so that I don't have to pass them over and over
public static TableLayoutPanel movingBox;
public static Form mainForm;
// Initialize
public Main()
{
InitializeComponent();
Main.mainForm = this;
Main.movingBox = tableLayoutPanel1;
}
// Button that runs thread which will move the blue box down
private void button1_Click(object sender, EventArgs e)
{
new Thread(
new ThreadStart(
() =>
{
SlideBoxDown();
}
)
).Start();
}
// Delegate
delegate void SlideBoxDownCallback();
// Slide box down
private static void SlideBoxDown()
{
if (Main.movingBox.InvokeRequired)
{
SlideBoxDownCallback d = new SlideBoxDownCallback(SlideBoxDown);
Main.mainForm.Invoke(d, new object[] { });
}
else
{
for (int i = 0; i < 20; i++)
{
Main.movingBox.Location = new Point(Main.movingBox.Location.X, Main.movingBox.Location.Y + 2);
Thread.Sleep(100);
//Application.DoEvents();
}
}
}
}
}
Application layout