如何在后台运行任务时在WPF中旋转图像?

时间:2016-09-19 16:53:56

标签: c# wpf

我有一个WPF应用程序,其中有一个启动按钮,执行一些Web服务调用,返回一些我使用oxyplot绘制在图表上的结果。我在UI上有一个图像,我想用作"微调器"直到任务完成。

我能够使用按钮点击路由事件来旋转我的图像,但我希望它一直旋转,直到我的网络服务调用完成。有什么建议吗?

 <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>

这是我的按钮点击方法:

      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;

    }

1 个答案:

答案 0 :(得分:0)

您需要使用处理事件的Async和Await方法。我没有足够的代码来为您提供正确的名称,但这就是我解决问题的方法

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

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