0

我需要做一个长期运行的任务。我通过在 UI 上有一个加载框时执行任务来完成此操作。当抛出异常时,我想停止任务并向用户显示一个 msgbox。如果一切顺利,我会停止加载箱。

下面的代码按预期工作,但我想知道我在这里是否正确,因为这是我第一次做这样的事情。

    private readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

    protected void ProgramImage()
    {
        this.OnProgrammingStarted(new EventArgs());
        var task =
            Task.Factory.StartNew(this.ProgramImageAsync)
                .ContinueWith(
                    this.TaskExceptionHandler,
                    cancellationTokenSource.Token,
                    TaskContinuationOptions.OnlyOnFaulted,
                    TaskScheduler.FromCurrentSynchronizationContext())  //Catch exceptions here
                        .ContinueWith(
                            o => this.ProgramImageAsyncDone(),
                            cancellationTokenSource.Token,
                            TaskContinuationOptions.NotOnFaulted,
                            TaskScheduler.FromCurrentSynchronizationContext());  //Run this when no exception occurred
    }

    private void ProgramImageAsync()
    {
        Thread.Sleep(5000); // Actual programming is done here
        throw new Exception("test");
    }

    private void TaskExceptionHandler(Task task)
    {
        var exception = task.Exception;
        if (exception != null && exception.InnerExceptions.Count > 0)
        {
            this.OnProgrammingExecuted(
                new ProgrammingExecutedEventArgs { Success = false, Error = exception.InnerExceptions[0] });
            this.Explanation = "An error occurrred during the programming.";
        }
        // Stop execution of further taks
        this.cancellationTokenSource.Cancel();
    }

    private void ProgramImageAsyncDone()
    {
        this.OnProgrammingExecuted(new ProgrammingExecutedEventArgs { Success = true });
        this.Explanation = ResourceGeneral.PressNextBtn_Explanation;
        this.IsStepComplete = true;
    }

该事件OnProgrammingStarted在 UI 线程上显示加载框。该事件OnProgrammingExecuted停止此加载框并显示一条消息,无论编程是否成功完成。两者都将 UI 线程作为订阅者。

4

1 回答 1

0

我也在Code Review上问过这个问题,因为这里不完全适合它。对于那些偶然发现这个问题并想知道答案的人:你可以在这里找到它

于 2013-06-07T11:06:03.507 回答