Reputation: 71
I wonder how to start my Server connection (simple button click that take 2 sec) without my UI freeze and after the connection established update my UI, i can do it via BackgroundWorker
and inside worker_RunWorkerCompleted event
update my UI but because this is different thread i need to use Invoke
:
private void btnConnect_Click(object sender, EventArgs e)
{
btnConnect.Enabled = false;
BackgroundWorker worker = new BackgroundWorker();
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
worker.DoWork += worker_DoWork;
worker.RunWorkerAsync();
}
Start do work and connect:
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
try
{
// Establish the connection...
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
And after the connection established update my UI:
private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// Update UI
}
My question is can i avoid using invoke ?
because in my application i have several points that i need to add, remove, update labels, DatagridView and in this way i'll have using Invoke
several times, this is a common and proper to do this?
There is a way to start something in different thread and after this thread ends remain to the main thread ?
Upvotes: 1
Views: 2020
Reputation: 3280
You do not need Invoke
in the following callbacks:
ProgressChanged
RunWorkerCompleted
Here you can access the UI elements directly without problems. The rest needs Invoke
.
Upvotes: 4