예제 #1
0
 protected override void OnTaskStatuesChanged(AutomaticCancellationTaskResult <int> taskResult)
 {
     Application.Current.Dispatcher.Invoke(() =>
     {
         Application.Current.MainWindow.Title = taskResult.TaskStatus.ToString();
     });
 }
        protected AutomaticCancellationTask(TimeSpan timeoutSpan)
        {
            cancellationResons = CancellationResons.None;
            cts        = new AutomaticCancellationTokenSource(timeoutSpan);
            tcs        = new TaskCompletionSource <T>();//<object>();
            workThread = new Thread(() =>
            {
                try
                {
                    OnTaskStart();
                    var result = OnTaskDoing();
                    if (!IsCancellationRequested)
                    {
                        tcs.SetResult(result);
                        OnTaskEnd();
                    }
                }
                catch (ThreadAbortException tae)
                {
                    Thread.ResetAbort();
                }
                catch (Exception e)
                {
                    tcs.SetException(e);
                }
            });
            workThread.IsBackground    = true;
            cts.CancellationRequested += Cts_CancellationRequested;
            tcs.Task.ContinueWith(p =>
            {
                T result    = default(T);
                Exception e = null;
                if (p.IsCanceled)
                {
                    result = default(T);
                }
                else if (p.IsFaulted)
                {
                    e = p.Exception;
                }
                else
                {
                    result = p.Result;
                }

                var taskresult =
                    AutomaticCancellationTaskResult <T> .BuildResult(p.Status, cancellationResons, result, e);
                try
                {
                    OnTaskStatuesChanged(taskresult);
                }
                catch (Exception c)
                {
                    OnTaskError(taskresult, c);
                }
            });
            workThread.Start();
        }
 /// <summary>Initializes a new instance of the <see cref="T:System.EventArgs" /> class.</summary>
 public TaskErrorEventArgs(AutomaticCancellationTaskResult <T> taskResult, Exception innerException)
 {
     TaskResult       = taskResult;
     HandeResultError = innerException;
 }
 protected abstract void OnTaskStatuesChanged(AutomaticCancellationTaskResult <T> taskResult);
 protected virtual void OnTaskError(AutomaticCancellationTaskResult <T> e, Exception innerException)
 {
     TaskError?.Invoke(this, new TaskErrorEventArgs <T>(e, innerException));
 }