Skip to main content
 首页 » 编程设计

c#之WPF MVVM 等待 : Cancel task does not stop my progressbar

2024年02月06日14JustinYoung

我正在研究 .NET 4.5 小型 WPF/MVVM 项目,我正在尝试让进度条与 async/await 一起正常工作。

我已经让事情正常工作,但我无法正确取消任务。或者,我认为任务可能被取消了,但无论如何进度条都在运行。

我在“开始”和“停止”时调用“LongRun”方法,但在我想停止时使用可选的取消标记参数。这可能是一种不寻常的做事方式,但我认为它看起来不错 - 至少在理论上 :-)

下面是一些代码:

View 模型

public MainViewModel() 
    { 
        _progress = new Progress<int>(ReportProgress); 
        CountFilesCreatedCommand = new RelayCommand<IProgress<int>>(progress => LongRun(Progress)); 
        _tokenSource = new CancellationTokenSource(); 
        _tokenSource.Cancel(); 
        StopCountFilesCommand = new RelayCommand<CancellationToken>(token => LongRun(Progress, _tokenSource.Token)); 
        ProgressText = "..."; 
    } 
 
    private void ReportProgress(int result) 
    { 
        PercentProgress = result; 
    } 
 
    private async void LongRun(IProgress<int> progress, CancellationToken token = default(CancellationToken)) 
    { 
        try 
        { 
            // Start long running task here 
            int i = 0; 
            for (; i != 101; ++i) 
            { 
                if (token.IsCancellationRequested) 
                { 
                    // This part of the code is executed when I 
                    // try to stop the Task, I can see the "Cancelled!" 
                    // text flicker for a second, and then the code 
                    // resume to run 
                    _tokenSource.Cancel(); 
                    progress?.Report(PercentProgress); 
                    ProgressText = "Cancelled!"; 
                 } 
                await Task.Delay(TimeSpan.FromSeconds(0.1), token).ConfigureAwait(false); 
                                    progress?.Report(i); 
                ProgressText = i + "%"; 
            } 
        } 
        catch (OperationCanceledException) 
        { 
 
            //throw; 
        } 
    } 

XAML

<Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"> 
    <StackPanel> 
        <!--<Button Margin="10,18,10,0" Content="Start Long Run" Height="30" Click="Button_Click_Async"/>--> 
        <ProgressBar x:Name="pbStatus" Margin="10,10,10,0" Height="30" IsIndeterminate="False" Visibility="Visible" Minimum="0" Maximum="100" Value ="{Binding PercentProgress, Mode=TwoWay}"/> 
        <TextBlock x:Name="tbResultat" Margin="0,10,0,10" HorizontalAlignment="Center" VerticalAlignment="Center" Text="{Binding ProgressText}" /> 
        <DockPanel> 
            <Button Margin="10,0" Content="Start Long Run" Height="30" Width="200" Command="{Binding CountFilesCreatedCommand}"/> 
            <Button Margin="10,0" Content="Stop Long Run" Height="30" Width="200" HorizontalAlignment="Right" Command="{Binding StopCountFilesCommand}"/> 
        </DockPanel> 
    </StackPanel> 
</Grid> 

我感觉该解决方案可能与 XAML 有关?

如有任何帮助,我们将不胜感激!

请您参考如下方法:

I am calling the "LongRun" method both on "Start" and "Stop", but with the optional cancellation token parameter when I want to stop.

这就是你的问题所在。当您停止时,您希望对 LongRun 的现有 调用存在,而不是创建对 LongRun 的新 调用。

这样的事情会更合适(假设这个操作只能完成一次,并且您根据需要启用/禁用按钮):

_progress = new Progress<int>(ReportProgress); 
_tokenSource = new CancellationTokenSource(); 
CountFilesCreatedCommand = new RelayCommand(() => LongRun(_progress, _tokenSource.Token)); 
StopCountFilesCommand = new RelayCommand(() => _tokenSource.Cancel()); 
ProgressText = "..."; 

附带说明,您应该 avoid async void (如我在 MSDN 文章中所述)。 async void 具有笨拙的错误处理语义,并且不可进行单元测试。