The answer code is right, but it’s hard to understand.
Simpler:
private void buttonSendUsers_Click(object sender, EventArgs e)
{
buttonSendUsers.Enabled = false;
Task.Run(() => {
// Sua tarefa aqui
Thread.Sleep(3000);
buttonSendUsers.Enabled = true;
});
}
If you use the above code, you will have an error in debugging time, but at runtime it works normally.
Error:
System.Invalidoperationexception: 'Invalid thread operation: buttonSendUsers control accessed from a thread that is not the one in which it was created.'
The error is due to calling interface objects in a Thread that is not that of the interface, there are two ways not to occur error:
Disabling extra conference at debug time
Call the next code in the form (not recommended to do this as you may have sync issues):
CheckForIllegalCrossThreadCalls = false;
It simply disables this conference at debug time.
Invoking Method in Interface Thread
calling:
Invoke((Action)(() => { buttonSendUsers.Enabled = true; }));
Or:
BeginInvoke((Action)(() => { buttonSendUsers.Enabled = true; }));
To rehabilitate the button, the second form does so asynchronously.
Code "thread safe":
private void buttonSendUsers_Click(object sender, EventArgs e)
{
buttonSendUsers.Enabled = false;
Task.Run(() => {
// Sua tarefa aqui
Thread.Sleep(3000);
BeginInvoke((Action)(() => { buttonSendUsers.Enabled = true; }));
});
}