Reputation: 686
I have the following Thread method:
public void messageDelay()
{
Thread.Sleep(5000);
}
But when I call it, it hand the UI interface and I can not done any operation until the thread is finished.
private void Porcessing_Click(object sender, EventArgs e)
{
label1.Text = "start under process..";
messageDelay();
label1.Text = "Result";
}
This is my main method. Any idea whats wrong I do?
Upvotes: 0
Views: 83
Reputation: 39956
You need to use Asynchronous programming in this case. It is essential for activities that are potentially blocking, such as yours:
private async void Porcessing_Click(object sender, EventArgs e)
{
label1.Text = "start under process..";
await messageDelay();
label1.Text = "Result";
}
public async Task messageDelay()
{
await Task.Delay(5000);
}
Note the use of async
all the way down. Check this also https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html
Upvotes: 2
Reputation: 26
You can use BackgroundWorker
. This class create another thread, so UI thread will not block. For example:
private void Porcessing_Click(object sender, EventArgs e)
{
var worker = new BackgroudWorker();
label1.Text = "start under process..";
worker.DoWork+=BackgroudAction;
worker.RunWorkerCompleted+=BackgroudActionEnd;
worker.RunWorkerAsync();
}
private void BackgroudAction(object sender, DoWorkEventArgs e)
{
Thread.Sleep(5000);
}
private void BackgroudActionEnd( object sender,RunWorkerCompletedEventArgs e)
{
label1.Text="Result";
}
Upvotes: 0