I got a function called Connect() this function takes about 2-3seconds because it use some api requests. Now I want to find a way that my Ui dont freeze while ill start this function.
private void connectToolStripMenuItem_Click(object sender, EventArgs e)
{
Connect() // << this tooks a lot of time
}
I have tried to solve it with a thread
private void connectToolStripMenuItem_Click(object sender, EventArgs e)
{
new Thread(Connect).Start();
}
and a backgroudnworker
private void backgroundWorkerConnect_DoWork(object sender, DoWorkEventArgs e)
{
Connect();
}
but the programm still freezes.
private void Connect()
{
if (InvokeRequired)
{
Invoke(new MethodInvoker(Connect));
}
else
{
if (!connected)
{
connected = true;
verbindenToolStripMenuItem.Enabled = false;
trennenToolStripMenuItem.Enabled = true;
InfoStripStatus.Text = "Status: Connected";
irc.joinRoom(channel, BotConnectingMessage);
chatThread = new Thread(getMessage);
chatThread.Start();
loadLoyalty();
updateTimer = new System.Threading.Timer(timerViewer, null, 0, 60000);
}
}
}
Maybe I'm just doing something wrong and hope someone can help me.
Using another thread (whether via
BackgroundWorker
or by creating one directly) to call a method that does nothing more than to invoke some code back on the UI thread and then wait for it, is going to solve nothing. The code you care about is still executing in the UI thread, blocking it.You should use
async
/await
withTask.Run()
to handle your work:Depending on how slow
loadLoyalty()
is, you might also wantawait Task.Run(loadLoyalty);
instead of just calling it directly.The above will execute all of the code in the UI thread where it belongs, except the code you invoke via
Task.Run()
.There are other ways that the code could be refactored, including an alternative that works with
BackgroundWorker
(i.e. just usingControl.Invoke()
to do the first four statements, and run the rest in theConnect()
method directly). But IMHO the above usingasync
/await
is the best option today.Okay that looks interessting. I will try to transfer it to the other functions because I found out that it is the updateTimer which freeze it.
so i will read more about ascny and await and test it a bit