user6849787 user6849787 - 2 months ago 21
C# Question

How do I make an image spin in WPF while running a task in the background?

I have a WPF application in which theres a start button that performs some web service calls, which return some results that I plot on a graph using oxyplot. I have an image on the UI that I would like to use as the "spinner" until the task has completed.

I'm able to use a button click routed event to spin my image but I want it to keep spinning until my web service calls are completed. Any suggestions?

<Button.Triggers>
<EventTrigger RoutedEvent="Button.Click">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetName="capIcon" Storyboard.TargetProperty="RenderTransform.Angle" By="90" Duration="0:0:1" />
<DoubleAnimation Storyboard.TargetName="capIcon" Storyboard.TargetProperty="RenderTransform.Angle" By="90" Duration="0:0:1" />
<DoubleAnimation Storyboard.TargetName="capIcon" Storyboard.TargetProperty="RenderTransform.Angle" By="90" Duration="0:0:1" />
<DoubleAnimation Storyboard.TargetName="capIcon" Storyboard.TargetProperty="RenderTransform.Angle" By="90" Duration="0:0:1" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Button.Triggers>


And here is my Button Click Method:

private void Button_Click_1(object sender, RoutedEventArgs e)
{
if (!validateThreadCount())
return;

RunTimes.runTimes.Clear();
//this.Plot.InvalidateFlag = 1;
int threads = Convert.ToInt16(this.ThreadCount.Text);

Task[] tasks = new Task[threads];
for (int i = 0; i < threads; i++)
{
DealClient dealClient = new DealClient();
var t = Task.Factory.StartNew(() => dealClient.NewDeal(1));
tasks[i] = t;
}

Task.WaitAll(tasks);

var points = new List<ScatterPoint>();
for (int i = 0; i < RunTimes.runTimes.Count; i++)
{
points.Add(new ScatterPoint(RunTimes.runTimes[i].Milliseconds, i, 3));
}

this.pts.ItemsSource = points;

}

Answer

You Need to use an Async and Await method which handles the event. I don't have enough of your code to give you proper names but this is how I would approach the problem

Private async Task MethodThatHandlesEvent()
{
 await Task.Run(() => 
     {
         RunWebService();
            While(WebServiceIsRunning)
            {MakeImagesSpin();}
     });
}

Private async void MyButton_Click()
{
    await MethodThatHandlesEvent();
}