小编Ser*_*nik的帖子

如何在 TPL 中处理任务取消

再会!我正在为 WinForms UI 编写一个帮助程序库。开始使用 TPL async/await 机制并遇到这种代码示例的问题:

    private SynchronizationContext _context;

    public void UpdateUI(Action action)
    {
        _context.Post(delegate { action(); }, null);
    }


    private async void button2_Click(object sender, EventArgs e)
    {

        var taskAwait = 4000;
        var progressRefresh = 200;
        var cancellationSource = new System.Threading.CancellationTokenSource();

        await Task.Run(() => { UpdateUI(() => { button2.Text = "Processing..."; }); });

        Action usefulWork = () =>
        {
            try
            {
                Thread.Sleep(taskAwait);
                cancellationSource.Cancel();
            }
            catch { }
        };
        Action progressUpdate = () =>
        {
            int i = 0;
            while …
Run Code Online (Sandbox Code Playgroud)

c# task task-parallel-library cancellation async-await

2
推荐指数
1
解决办法
1398
查看次数