【问题标题】:Centralize before and after actions around a new task created by TPL围绕 TPL 创建的新任务集中前后操作
【发布时间】:2012-05-15 02:37:23
【问题描述】:

在我们的应用程序中,每当我们想要进行服务调用时,我们都会使用 TPL 创建任务。我们有一个忙碌指示器,当任务启动时设置为真,当任务完成或出错时清除。有有什么方法可以以通用方式完成此任务,而不是为创建的每个任务都执行此操作?

一审:

        ComponentViewModel.Instance.IsApplicationBusy = true;
        ComponentViewModel.Instance.BusyMessage = "Loading...";

        var task1 = Task.Factory.StartNew(() => DoTask1());
        task1.ContinueWith(antecdent =>
        {
            ComponentViewModel.Instance.IsApplicationBusy = false;
            CustomAction1();
        }

二审:

        ComponentViewModel.Instance.IsApplicationBusy = true;
        ComponentViewModel.Instance.BusyMessage = "Loading...";

        var task2 = Task.Factory.StartNew(() => DoTask2());
        task2.ContinueWith(antecdent =>
        {
            ComponentViewModel.Instance.IsApplicationBusy = false;
            CustomAction2();
        }

每当进行服务调用时,整个应用程序都会重复逻辑,有什么方法可以避免这种重复吗?

例如,所有拖动操作都会触发一个 dragstarted 和 dragcompleted 事件,因此可能通过扩展任务工厂或其他方式来产生 taskstarted 和 taskcompleted 事件?

编辑:进行了更改以使问题更加清晰。您现在可以观察到开始和结束任务之前的步骤是相同的​​,但是当每个任务运行完成时需要为每个任务执行不同的功能

【问题讨论】:

    标签: c# wpf task-parallel-library busyindicator


    【解决方案1】:

    编辑:看来我误解了这个问题。创建这个“开始、等待、继续”作为一个集中式函数是一个很好的举措,可以这样创建:

    public void DoIt(Action ThingToDo) {
        ComponentViewModel.Instance.IsApplicationBusy = true;
        ComponentViewModel.Instance.BusyMessage = "Loading...";
    
        var loadProviderTask = Task.Factory.StartNew(ThingToDo);
        loadProviderTask.ContinueWith(antecdent =>
        {
            ComponentViewModel.Instance.IsApplicationBusy = false;
        }
    }
    

    【讨论】:

    • 嗨,对不起,我的问题不清楚。我已经编辑了问题。我希望在任务完成后执行不同的功能
    • @VasudevanKannan,然后只需将它作为另一个委托参数传递给函数并在继续中调用它。
    • @robrich,你是说Task.Factory.StartNew(ThingToDo)吗?此外,.Net 中通常的命名约定是以小写字母开头的参数。
    • 公共静态任务 DoTaskWithBusyIndi​​cator(Action thingToDo,Action completionTask) { ComponentViewModel.Instance.IsApplicationBusy = true; ComponentViewModel.Instance.BusyMessage = "加载中..."; var task = Task.Factory.StartNew(Action); task.ContinueWith(antecdent => { ComponentViewModel.Instance.IsApplicationBusy = false; completionTask(); } return task; }
    • @svick,我做了一些小改动并发表了评论。任何人仍然对创建 taskstarted 和 taskcompleted 事件的想法感兴趣,因为此解决方案涉及创建多个重载,并且使用 taskcreationoptions 和任务继续选项等
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-14
    • 1970-01-01
    • 2011-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多