c# - 如何在 wpf 后台执行任务,同时能够提供报告并允许取消?

标签 c# wpf task-parallel-library

我想在单击 wpf 按钮后执行长时间运行的任务。这是我所做的。

private void Start(object sender, RoutedEventArgs e)
{
    for (int i = 0; i < 10; i++)
    {
        Thread.Sleep(2000); // simulate task
    }
}

问题是,这会使 wpf gui 无响应。我还想允许取消并每 1 秒报告一次进度。我将代码展开如下。

    DispatcherTimer dispatcherTimer = new DispatcherTimer(); // get progress every second
    private int progress = 0; // for progress reporting
    private bool isCancelled = false; // cancellation

    private void Start(object sender, RoutedEventArgs e)
    {
        InitializeTimer(); // initiallize interval timer 
        Start(10); // execute task
    }

    private void InitializeTimer()
    {
        dispatcherTimer.Tick += dispatcherTimer_Tick;
        dispatcherTimer.Interval = new TimeSpan(0,0,1);
        dispatcherTimer.Start();
    }

    private void dispatcherTimer_Tick(object sender, EventArgs e)
    {
        Logger.Info("Current loop progress " + progress); // report progress
    }

    private void Cancel(object sender, RoutedEventArgs e) // cancel button
    {
        isCancelled = true;
    }

    private int Start(int limit)
    {
        isCancelled = true;
        progress = 0;

        for (int i = 0; i < limit; i++)
        {
            Thread.Sleep(2000); // simulate task
            progress = i; // for progress report
            if (isCancelled) // cancellation
            {
                break;
            }
        }
        return limit;
    }

我的目标平台是 .NET 4.5。推荐的方法是什么?

谢谢。

最佳答案

我以为我回答了你的问题 here .如果您需要有关如何使用任务并行库执行此操作的更多示例代码,请使用 CancellationTokenSourceIProgress<T> ,这里是:

Action _cancelWork;

private async void StartButton_Click(object sender, RoutedEventArgs e)
{
    this.StartButton.IsEnabled = false;
    this.StopButton.IsEnabled = true;
    try
    {
        var cancellationTokenSource = new CancellationTokenSource();

        this._cancelWork = () => 
        {
            this.StopButton.IsEnabled = false;
            cancellationTokenSource.Cancel();
         };

        var limit = 10;

        var progressReport = new Progress<int>((i) => 
            this.TextBox.Text = (100 * i / (limit-1)).ToString() + "%");

        var token = cancellationTokenSource.Token;

        await Task.Run(() =>
            DoWork(limit, token, progressReport), 
            token);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    this.StartButton.IsEnabled = true;
    this.StopButton.IsEnabled = false;
    this._cancelWork = null;
}

private void StopButton_Click(object sender, RoutedEventArgs e)
{
    this._cancelWork?.Invoke();
}

private int DoWork(
    int limit, 
    CancellationToken token,
    IProgress<int> progressReport)
{
    var progress = 0;

    for (int i = 0; i < limit; i++)
    {
        progressReport.Report(progress++);
        Thread.Sleep(2000); // simulate a work item
        token.ThrowIfCancellationRequested();
    }
    return limit;
}

关于c# - 如何在 wpf 后台执行任务,同时能够提供报告并允许取消?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21348125/

相关文章:

C# 将字符串拆分为单独的变量

c# - 使用 MVC ViewContext 渲染 View 时指定样式表媒体

c# - WPF 应用程序中的复合 ViewModel

c# - WPF ControlTemplate 从父资源继承样式

c# - 如何使用同步方法将异步方法的返回值传递到同步类中

c# - 异步事件处理程序和并发

c# - 在 C# 中定义 F# '**' 运算符

C# 单一项目组织

c# - 在 VS 2013 中使用报表查看器

c# - 限制没有。每秒由 Dns.BeginGetHostEntry 方法生成的请求数或使用任务并行库 (TPL)