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

本文关键字:后台 运行 任务 图像 WPF 旋转 | 更新日期: 2023-09-27 18:07:33

我有一个WPF应用程序,其中有一个开始按钮,该按钮执行一些web服务调用,返回一些结果,我使用oxyplot在图上绘制。我在UI上有一个图像,我想用它作为"旋转器",直到任务完成。

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

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

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

你需要使用Async和Await方法来处理事件。我没有足够的代码来给你们取合适的名字但这就是我要解决的问题

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