/// <summary> /// Starts a background task with the given parameter that runs on a parallel thread. Shall be called from the UI-thread. /// </summary> /// <param name="task">The starting method of the task.</param> /// <param name="name">The name of the executing thread of the task.</param> /// <param name="parameter">The starting parameter of the task.</param> /// <returns>A reference to the interface of the created task.</returns> public static IUIBackgroundTask StartParallelTask(UIParallelTaskMethod task, string name, object parameter) { if (uiThread != null && RCThread.CurrentThread != uiThread) { throw new InvalidOperationException("UITaskManager.StartParallelTask shall be called from the UI-thread!"); } if (calledFromUi) { throw new InvalidOperationException("Recursive call on UITaskManager!"); } if (task == null) { throw new ArgumentNullException("task"); } if (name == null) { throw new ArgumentNullException("name"); } calledFromUi = true; uiThread = RCThread.CurrentThread; RCThread taskThread = new RCThread(ParallelTaskProc, name); UIParallelTask taskData = new UIParallelTask(task, parameter); lock (runningParallelTasks) { runningParallelTasks.Add(taskThread, taskData); } taskThread.Start(taskData); calledFromUi = false; return(taskData); }
/// <summary> /// Posts a message back to the UI-thread. Shall not be called from the UI-thread in case of parallel tasks. /// </summary> /// <param name="message">The message to post.</param> public static void PostMessage(object message) { if (uiThread == null) { throw new InvalidOperationException("UITaskManager.PostMessage shall not be called before calling UITaskManager.StartParallelTask, UITaskManager.StartTimeSharingTask or UITaskManager.OnUpdate!"); } if (message == null) { throw new ArgumentNullException("message"); } if (uiThread == RCThread.CurrentThread) { /// Call from a time sharing task if (scheduledTask == null) { throw new InvalidOperationException("UITaskManager.PostMessage can be called from the UI-thread only if a time sharing task has been scheduled!"); } scheduledTask.PostMessage(message); } else { /// Call from a parallel task. lock (runningParallelTasks) { UIParallelTask task = runningParallelTasks[RCThread.CurrentThread]; task.PostMessage(message); } } }
/// <summary> /// The starting method of the parallel tasks. /// </summary> /// <param name="taskData">The UIParallelTask object itself.</param> private static void ParallelTaskProc(object taskData) { UIParallelTask task = (UIParallelTask)taskData; try { TraceManager.WriteAllTrace(string.Format("Starting task '{0}'", RCThread.CurrentThread.Name), UITraceFilters.INFO); task.TaskProc(task.Parameter); task.PostFinish(); TraceManager.WriteAllTrace(string.Format("Task '{0}' finished", RCThread.CurrentThread.Name), UITraceFilters.INFO); } catch (Exception ex) { TraceManager.WriteAllTrace(string.Format("Task '{0}' failed. Exception: {1}", RCThread.CurrentThread.Name, ex.ToString()), UITraceFilters.ERROR); task.PostFailure(ex); } }