public static Task CreateHandledTask(TaskScheduled mainTask, TaskScheduled onSuccessTask, TaskScheduled onCancelationTask, TaskCreationOptions tco, CancellationToken cancellationToken, params TaskScheduled[] timeouts) { Task tsk = null; ManualResetEvent me = new ManualResetEvent(false); if (timeouts == null || timeouts.Length < 1 || timeouts[0] == null) { tsk = CreateHandledTask(mainTask.action, tco, cancellationToken); me.Set(); } else { bool isCancelation = false; bool isSuccess = true; Task NonBlockCtxTask = CreateHandledTask(() => { tsk = CreateHandledTask(mainTask.action, tco, cancellationToken); me.Set(); int qtdt = timeouts.Count(st => st.action != null); CountdownEvent cde_pas = new CountdownEvent(3); CountdownEvent cde_pat = new CountdownEvent(qtdt); Parallel.ForEach <TaskScheduled>(timeouts, (ts) => { try { bool itsOnTime = tsk.Wait(ts.waitTime, cancellationToken); cde_pat.Signal(); if (!itsOnTime) { isSuccess = false; Task tact = CreateHandledTask(ts.action, TaskCreationOptions.None, cancellationToken); } } catch (OperationCanceledException oce) { isSuccess = false; cde_pat.Signal(cde_pat.CurrentCount); isCancelation = true; } }); try { isSuccess &= cde_pat.Wait(System.Threading.Timeout.Infinite, cancellationToken) && !isCancelation; } catch (OperationCanceledException oce) { isCancelation = true; isSuccess = false; } finally { cde_pas.Signal(); } try { if (isCancelation && onCancelationTask != null) { Thread.Sleep(onCancelationTask.waitTime); Task tcn = CreateHandledTask(onCancelationTask.action); } } catch { } finally { cde_pas.Signal(); } try { if (isSuccess && onSuccessTask != null) { Thread.Sleep(onSuccessTask.waitTime); Task tcn = CreateHandledTask(onSuccessTask.action); } } catch { } finally { cde_pas.Signal(); } cde_pas.Wait(System.Threading.Timeout.Infinite); }, TaskCreationOptions.None, cancellationToken); } me.WaitOne(); return(tsk); }
private void ScheduleInternal(TaskContext context) { queue.Enqueue(context); TaskScheduled?.Invoke(this, new TaskEventArgs(context.Tag)); Next(cts.Token); }