0
장기간 실행해야하는 작업이 있습니다. UI에 로딩 박스가있을 때 Task를 실행하여이 작업을 수행했습니다. 예외가 발생하면 작업을 중지하고 msgbox를 사용자에게 보여주고 싶습니다. 모든 일이 올바르게 진행되면 적재 상자를 멈 춥니 다.작업 : 예외 및 취소
아래의 코드는 예상대로 작동하지만이 경우 처음으로 내가 이처럼 somehting을하고 있기 때문에 올바른지 알고 싶습니다.
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 스레드가 있습니다.