任务完成后如何调用方法?

时间:2017-07-28 09:02:43

标签: c# task

您好我试图在所有图片都经过适当深度缩放和压缩后提醒用户。每个图像都被异步深度缩放和压缩,并且在所有图像成功进行深度缩放和压缩后,我希望通过弹出窗口提醒用户。

var z = Task.Factory.StartNew(
() =>
{
    cr.Create(current_file_name, output);
    File.Copy(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\HTMLViewer.html", outputPath + "\\HTMLViewer.html", true);

    ZipFile.CreateFromDirectory(outputPath, Directory.GetParent(outputPath) + "\\" + Path.GetFileNameWithoutExtension(current_file_name) + ".zip");
});

var tasks = new[] { z };
var continued = Task.WhenAll(tasks).ContinueWith((antecedent) =>
{
    _window.MainDispatcher.BeginInvoke(new Action(
    () =>
    {
        _popUp.PopUpText = "DeepZoom completed";
        _popUp.BeginPopUpTimer();
    }));
}, TaskContinuationOptions.OnlyOnRanToCompletion); 

我使用了以下解决方案作为示例:https://stackoverflow.com/questions/12248832/how-to-check-that-all-tasks-have-been-properly-completed#=但我似乎无法使其正常运行。所以只是为了澄清;此代码位于循环中,遍历一组图像。当所有图像都已成功压缩后,我希望调用_popUp.BeginPopUpTimer方法。

2 个答案:

答案 0 :(得分:2)

尝试使用async await

from collections import Counter
c = Counter(d["key"] for d in dicts if d["key"] != 'a')
print c.most_common()[0]

当您只有一项任务时,您不必使用private async Task DoMyWork() { var z = Task.Factory.StartNew( () => { cr.Create(current_file_name, output); File.Copy(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\HTMLViewer.html", outputPath + "\\HTMLViewer.html", true); ZipFile.CreateFromDirectory(outputPath, Directory.GetParent(outputPath) + "\\" + Path.GetFileNameWithoutExtension(current_file_name) + ".zip"); }); var tasks = new[] { z }; await Task.WhenAll(tasks); _window.MainDispatcher.BeginInvoke(() => { _popUp.PopUpText = "DeepZoom completed"; _popUp.BeginPopUpTimer(); }); } 。您可以使用:

Task.WhenAll

答案 1 :(得分:0)

  

如何在任务完成后调用方法?

使用UserModel

此外:

应用这些最佳实践,代码大大简化:

IProgress<T>