栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在wpf后台执行任务同时提供报告并允许取消?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在wpf后台执行任务同时提供报告并允许取消?

我以为我在这里回答了你的问题。如果您需要有关如何使用Task
Parallel Library进行操作的更多示例代码,请使用

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/483999.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号