I write the following event handler in MainWindow.xaml.cs
. I want to achieve such an effect,when the business logic is running the runbutton's background image switches to powerOnOff1.png
, when the business logic is finished the background image switches back to powerOnOff0.png
.
private void Run_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
//set run button background image to powerOnOff1.png indicates business logic is going to run.
BitmapImage ima0 = new BitmapImage(new Uri("picture/powerOnOff1.png", UriKind.Relative));
image.Source = ima0;
//business logic
......
//restore Runbutton background image to powerOnOff0.png indicates business logic is finished.
BitmapImage ima1 = new BitmapImage(new Uri("picture/powerOnOff0.png", UriKind.Relative));
image.Source = ima1;
}
Above codes doesn't work. It always show powerOnOff0.png
background image. Does it require multi-threading?
Does it require multithreading?
Yes. You need execute the business logic on a background thread. The easiest way to do this would be to start a new task and await it:
private async void Run_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
//set run button background image to powerOnOff1.png indicates business logic is going to run.
image.Source = new BitmapImage(new Uri("picture/powerOnOff1.png", UriKind.Relative));
await Task.Run(() =>
{
//business logic here
});
//restore Runbutton background image to powerOnOff0.png indicates business logic is finished.
image.Source = new BitmapImage(new Uri("picture/powerOnOff0.png", UriKind.Relative));
}