static void Main(string[] args) { // create the first generation task Task firstGen = new Task(() => { Console.WriteLine("Message from first generation task"); // comment out this line to stop the fault throw new Exception(); }); // create the second generation task - only to run on exception Task secondGen1 = firstGen.ContinueWith(antecedent => { // write out a message with the antecedent exception Console.WriteLine("Antecedent task faulted with type: {0}", antecedent.Exception.GetType()); }, TaskContinuationOptions.OnlyOnFaulted); // create the second generation task - only to run on no exception Task secondGen2 = firstGen.ContinueWith(antecedent => { Console.WriteLine("Antecedent task NOT faulted"); }, TaskContinuationOptions.NotOnFaulted); // start the first generation task firstGen.Start(); // wait for input before exiting Console.WriteLine("Press enter to finish"); Console.ReadLine(); }
/// <summary> /// Initializes a new instance of the <see cref="RedisCache"/> class. /// </summary> /// <param name="configuration">The configuration.</param> public RedisCache(ConfigurationOptions configuration) { if (RedisCache.connection == null) { try { connectionTask = ConnectionMultiplexer.ConnectAsync(configuration); connectionTask.ContinueWith(t => { lock (syncronizationObject) { if (RedisCache.connection == null) RedisCache.connection = t.Result; } this.cache = RedisCache.connection.GetDatabase(); Trace.TraceInformation("Redis Cache Provider connection complete - Correlation Id = {0}", Trace.CorrelationManager.ActivityId); }); } catch (AggregateException age) { age.Handle(e => { Trace.TraceError("Redis Cache Provider error - Correlation Id = {0}\n {1}\n {2}", Trace.CorrelationManager.ActivityId, e.Message, e.StackTrace); return true; }); } catch (Exception ex) { Trace.TraceError("Redis Cache Provider exception - Correlation Id = {0}\n {1}\n {2}", Trace.CorrelationManager.ActivityId, ex.Message, ex.StackTrace); } } }
private static void Main(string[] args) { var task = new Task(() => { Console.WriteLine("Task 1 rolls out"); throw new Exception(); }); task.ContinueWith( task1 => Console.WriteLine("Task {0} nevermind of state, task result is {1}", task1.Id, task1.Status), TaskContinuationOptions.None); task.ContinueWith( task1 => Console.WriteLine("Task {0} failed, task result is {1}", task1.Id, task1.Status), TaskContinuationOptions.OnlyOnFaulted); task.ContinueWith( task1 => Console.WriteLine("Task {0} failed executing continuation syncchronously, task result is {1}", task1.Id, task1.Status), TaskContinuationOptions.ExecuteSynchronously); task.ContinueWith( task1 => Console.WriteLine("Task {0} runned outside the pool, task result is {1}", task1.Id, task1.Status), TaskContinuationOptions.OnlyOnCanceled); task.Start(); Console.ReadLine(); }
private void SetupSigninTaskContinuations(Task<LogOnInfo> signinTask, TaskCompletionSource<UserViewModel> taskCompletionSource) { signinTask.ContinueWith(completedTask => CompleteSignin(completedTask.Result, taskCompletionSource), TaskContinuationOptions.OnlyOnRanToCompletion); signinTask.ContinueWith(failedTask => HandleSigninException(failedTask.Exception, taskCompletionSource), TaskContinuationOptions.OnlyOnFaulted); taskCompletionSource.Task.ContinueWith( completedSignin => OnSigninComplete(completedSignin.Result, _logOnInfo.Rooms.Any()), TaskContinuationOptions.OnlyOnRanToCompletion); }
private void RunThreadFixApiAsync(Task apiTask, Action success) { var context = SynchronizationContext.Current; apiTask.ContinueWith(result => { context.Post(o => { success.Invoke(); }, null); }, TaskContinuationOptions.NotOnFaulted); apiTask.ContinueWith(error => { ToggleMenuCommands(true); ShowErrorMessage(error.Exception.InnerException.Message); }, TaskContinuationOptions.OnlyOnFaulted); }
public Task ProcessMessageAsync(string room, Message message) { var task = new Task<ChatMessageViewModel>(() => { ChatMessageViewModel msgVm = CreateMessageViewModel(message); return msgVm; }); task.ContinueWith(completedTask => OnMessageProcessed(completedTask.Result, room), TaskContinuationOptions.OnlyOnRanToCompletion); task.ContinueWith(ProcessTaskExceptions, TaskContinuationOptions.OnlyOnFaulted); task.Start(); return task; }
protected override void OnResume() { base.OnResume(); System.Threading.Tasks.Task startWork = new System.Threading.Tasks.Task(() => { System.Threading.Tasks.Task.Delay(3000); }); startWork.ContinueWith(t => { var auth = FirebaseAuth.Instance; if (auth.CurrentUser != null) { Intent intent = new Intent(Application.Context, typeof(HomeActivity)); StartActivity(intent); OverridePendingTransition(Resource.Animation.Side_in_right, Resource.Animation.Side_out_left); //Toast.MakeText(this, "toast", ToastLength.Long).Show(); Finish(); } else { Intent intent = new Intent(Application.Context, typeof(LoginSignupActivity)); StartActivity(intent); OverridePendingTransition(Resource.Animation.Side_in_right, Resource.Animation.Side_out_left); Finish(); } }, TaskScheduler.FromCurrentSynchronizationContext()); startWork.Start(); }
public AsyncResult(AsyncCallback callback, object state, Task task) { _state = state; _task = task; _completedSynchronously = _task.IsCompleted; _task.ContinueWith(t => callback(this), TaskContinuationOptions.ExecuteSynchronously); }
public void Track(Task task, string inprogressText) { pictureBox.Image = Resources.spin; label.Text = inprogressText; label.ForeColor = DefaultForeColor; toolTip.RemoveAll(); task .ContinueWith(t => { if (t.IsCanceled) { label.Text = "Cancelled"; label.ForeColor = Color.Peru; pictureBox.Image = Resources.Ok; } else if (t.IsFaulted) { pictureBox.Image = Resources.Error; label.Text = "ERROR"; label.ForeColor = Color.Red; toolTip.SetToolTip(pictureBox, t.Exception.InnerException.Message); toolTip.SetToolTip(label, t.Exception.InnerException.ToString()); } else { pictureBox.Image = Resources.Ok; label.Text = _rantoCompletionText; } }, TaskScheduler.FromCurrentSynchronizationContext()) ; }
public static void LaunchThread() { Task<Int32[]> parent = new Task<int[]>(() => { var results = new Int32[3]; // Use this factory configuration... TaskFactory tf = new TaskFactory(TaskCreationOptions.AttachedToParent, TaskContinuationOptions.ExecuteSynchronously); // ... to create tasks tf.StartNew(() => results[0] = 4); tf.StartNew(() => results[1] = 5); tf.StartNew(() => results[2] = 6); return results; }); parent.Start(); var finalTask = parent.ContinueWith( parentTask => { foreach (int i in parentTask.Result) Console.WriteLine(i); }); // Wait the task parent finished (and the child tasks finished) finalTask.Wait(); // Result : // 4 // 5 // 6 Console.ReadKey(); }
public static void Main() { bool parentTaskFaulted = false; Task task = new Task(() => { throw new InvalidOperationException(); }); Task continuationTask = task.ContinueWith( (antecedentTask) => { parentTaskFaulted = antecedentTask.IsFaulted; }, TaskContinuationOptions.OnlyOnFaulted); task.Start(); continuationTask.Wait(); Trace.Assert(parentTaskFaulted); if(!task.IsFaulted) { task.Wait(); } else { task.Exception.Handle(eachException => { Console.WriteLine( "ERROR: {0}", eachException.Message); return true; }); } }
internal static void MakeMsgToRequestDataCalc(int sensorid, string filePath, DateTime acqTime) { var msg = new RequestDataCalcMessage { Id = Guid.NewGuid(), SensorID = sensorid, DateTime = acqTime, FilePath = filePath, RoundNum = string.Empty }; System.Threading.Tasks.Task task = new System.Threading.Tasks.Task( () => { WarningThread.GetWarningThread().SendWarningProcessMessage(msg); }); task.Start(); task.ContinueWith( t => { if (t.Exception != null) { Log.Error("发送振动计算请求失败:" + t.Exception.Message, t.Exception); } else { Log.Info("发送振动计算请求成功"); } }); }
internal static void LogAndForget(this Task task, string source) => task.ContinueWith( (t, s) => VsShellUtilities.LogError(s as string, t.Exception?.ToString()), source, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.Default);
internal static void LogAndForget(this Task task, string source) => task.ContinueWith( (t, s) => VsShellUtilities.LogError(s as string, t.Exception.ToString()), source, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, VsTaskLibraryHelper.GetTaskScheduler(VsTaskRunContext.UIThreadNormalPriority));
public GeoViewModel(MetroTwitStatusBase Tweet) { this.ShowAnimation = true; this.LinkCommand = new RelayCommand<string>(new Action<string>(CommonCommands.OpenLink)); Coordinate coordinate = Tweet.Coordinates != null ? Tweet.Coordinates.Coordinate[0] : Tweet.Geo.BoundingBox.Coordinates[0]; if (coordinate != null) { Task task = new Task((Action) (() => this.GeoLookup(coordinate))); task.ContinueWith((Action<Task>) (t => CommonCommands.CheckTaskExceptions(t))); task.Start(); object resource = Application.Current.FindResource((object) "ModernColorFeature"); string PinColour = resource == null ? "blue" : "0x" + resource.ToString().Remove(0, 3); this.GeoImageURI = CoreServices.Instance.CurrentMapService.StaticMapURL(coordinate.Latitude, coordinate.Longitude, 320, 320, PinColour); GeoViewModel geoViewModel = this; double num = coordinate.Latitude; string str1 = num.ToString((IFormatProvider) CultureInfo.InvariantCulture.NumberFormat); string str2 = ", "; num = coordinate.Longitude; string str3 = num.ToString((IFormatProvider) CultureInfo.InvariantCulture.NumberFormat); string str4 = str1 + str2 + str3; geoViewModel.GeoPlaceText = str4; this.LiveMapURL = CoreServices.Instance.CurrentMapService.LiveMapURL(coordinate.Latitude, coordinate.Longitude); } this.ShowAnimation = false; }
void SaveSettings() { SetError(); if (MaxChatHistory.Value == null) MaxChatHistory.Value = 100; var dataDirectory = TextBoxDataDirectory.Text; var installOnBoot = CheckBoxInstallOnBoot.IsChecked ?? false; var useLightChat = CheckBoxLightChat.IsChecked ?? false; var useHardwareRendering = CheckBoxUseHardwareRendering.IsChecked ?? false; var useTransparentWindows = CheckBoxUseWindowTransparency.IsChecked ?? false; var maxChatHistory = MaxChatHistory.Value ?? 100; var enableChatImages = CheckBoxEnableChatImages.IsChecked ?? false; var enableChatGifs = CheckBoxEnableChatGifs.IsChecked ?? false; var task = new Task( () => this.SaveSettingsTask( ref dataDirectory, installOnBoot, useLightChat, useHardwareRendering, useTransparentWindows, maxChatHistory, enableChatImages, enableChatGifs)); task.ContinueWith((t) => { Dispatcher .Invoke(new Action( () => this.SaveSettingsComplete(t))); }); task.Start(); }
/// <summary> 开启新线程 </summary> public void NewTaskStart(decimal time, Int64 userid) { try { if (Variable.PrisonTask.ContainsKey(userid)) { return; } Variable.PrisonTask.TryAdd(userid, true); var token = new CancellationTokenSource(); var task = new System.Threading.Tasks.Task(() => SpinWait.SpinUntil(() => false, (int)time), token.Token); task.Start(); task.ContinueWith(m => { if (Variable.PrisonTask.ContainsKey(userid)) { var a = true; Variable.PrisonTask.TryRemove(userid, out a); PrisonOut(userid); } token.Cancel(); }, token.Token); } catch (Exception ex) { XTrace.WriteException(ex); } }
static void Main(string[] args) { // create a first generation task Task gen1 = new Task(() => { // write out a message Console.WriteLine("First generation task"); }); // create a second generation task Task gen2 = gen1.ContinueWith(antecedent => { // write out a message Console.WriteLine("Second generation task - throws exception"); throw new Exception(); }); // create a third generation task Task gen3 = gen2.ContinueWith(antecedent => { // write out a message Console.WriteLine("Third generation task"); }); // start the first gen task gen1.Start(); // wait for the last task in the chain to complete gen3.Wait(); // wait for input before exiting Console.WriteLine("Press enter to finish"); Console.ReadLine(); }
static GlobalVar() { DATA_PATH = Application.persistentDataPath; //DATA_PATH = DATA_PATH.Substring(0, DATA_PATH.Length - 5); // for Androj //DATA_PATH = DATA_PATH.Substring(0, DATA_PATH.LastIndexOf("/")); // for Androj DATA_PATH += "/Data"; DB_PATH = Application.persistentDataPath + "/db"; if (!Directory.Exists(DB_PATH)) { Directory.CreateDirectory(DB_PATH); } GameObject g = new GameObject("ShareContext"); shareContext = g.AddComponent <ShareContext>(); shareContext.initLoadingIndicator(); #if !UNITY_WEBGL && !UNITY_STANDALONE System.Collections.Generic.Dictionary <string, object> defaults = new System.Collections.Generic.Dictionary <string, object>(); defaults.Add("BASE_ASSET_DOWNLOAD_URL", "http://www.smallworld3d.com/unity3d/3dbook_test/"); Firebase.RemoteConfig.FirebaseRemoteConfig.SetDefaults(defaults); BASE_ASSET_DOWNLOAD_URL = Firebase.RemoteConfig.FirebaseRemoteConfig.GetValue("BASE_ASSET_DOWNLOAD_URL").StringValue; //DebugOnScreen.Log("RemoteConfig configured and ready with BASE_ASSET_DOWNLOAD_URL : " + BASE_ASSET_DOWNLOAD_URL); //DebugOnScreen.Log("RemoteConfig Fetching data..."); System.Threading.Tasks.Task fetchTask = Firebase.RemoteConfig.FirebaseRemoteConfig.FetchAsync( TimeSpan.Zero); fetchTask.ContinueWith(FetchComplete); #endif }
public IDisposable Subscribe(IObserver <SearchedFile> observer) { LoggingService.Debug("Parallel FindAll starting"); var task = new System.Threading.Tasks.Task( delegate { var list = fileList.ToList(); ThrowIfCancellationRequested(); SearchParallel(list, observer); }, TaskCreationOptions.LongRunning); task.ContinueWith( t => { LoggingService.Debug("Parallel FindAll finished " + (t.IsFaulted ? "with error" : "successfully")); if (t.Exception != null) { observer.OnError(t.Exception); } else { observer.OnCompleted(); } this.Dispose(); }); task.Start(); return(this); }
public static void LaunchThread() { Task<int[]> parent = new Task<int[]>(() => { var results = new int[3]; new Task(() => results[0] = 1, TaskCreationOptions.AttachedToParent).Start(); new Task(() => results[1] = 2, TaskCreationOptions.AttachedToParent).Start(); new Task(() => results[2] = 3, TaskCreationOptions.AttachedToParent).Start(); return results; }); parent.Start(); var finalTask = parent.ContinueWith( parentTask => { foreach (int i in parentTask.Result) Console.WriteLine(i); } ); // Wait the task parent finished (and the child tasks finished) finalTask.Wait(); // Result : // 1 // 2 // 3 Console.ReadKey(); }
/// <summary> /// /// </summary> /// <param name="task"></param> /// <param name="callback"></param> /// <param name="state"></param> /// <returns></returns> public static IAsyncResult ToBegin(Task task, AsyncCallback callback, object state) { if (task == null) throw new ArgumentNullException(nameof(task)); var tcs = new TaskCompletionSource<object>(state); task.ContinueWith(t => { if (task.IsFaulted) { if (task.Exception != null) tcs.TrySetException(task.Exception.InnerExceptions); } else if (task.IsCanceled) { tcs.TrySetCanceled(); } else { tcs.TrySetResult(null); //tcs.TrySetResult(RpcAction.GetTaskResult(t)); } callback?.Invoke(tcs.Task); }/*, TaskScheduler.Default*/); return tcs.Task; }
protected override Task Send(IList<Message> messages) { if (messages == null || messages.Count == 0) { var emptyTask = new TaskCompletionSource<object>(); emptyTask.SetResult(null); return emptyTask.Task; } if (_connection.State == ConnectionState.Disconnected) { startTask = _connection.Start(); startTask.ContinueWith(t => { throw t.Exception.GetBaseException(); }, TaskContinuationOptions.OnlyOnFaulted); } if (!startTask.IsCompleted) { startTask.Wait(); } return _connection.Send("s:"+messages.ToScaleoutString()); }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.Main); //create a new dialog dialog = CustomProgressDialog.CreateDialog(this); dialog.OnWindowFocusChanged(true); Button btnGO = FindViewById<Button>(Resource.Id.go); btnGO.Click += (s,e) => { int result = 0; //show the dialog dialog.Show(); //do some things Task task = new Task(() => { for (int i = 0; i < 100; i++) { result += i; } }); task.ContinueWith(t => { Intent intent = new Intent(this, typeof(LastActivity)); intent.PutExtra("name", result.ToString()); StartActivity(intent); }); task.Start(); }; }
public static Task CreateAndExecuteTaskContinueWith(Action BodyMethod, Action ContinueMethod, TaskCreationOptions t_Options = TaskCreationOptions.None) { Task t_task = new Task(BodyMethod, t_Options); t_task.ContinueWith(_ => ContinueMethod); t_task.Start(); return t_task; }
public static void Main() { bool parentTaskFaulted = false; Task task = new Task(() => { throw new ApplicationException(); }); Task faultedTask = task.ContinueWith( (parentTask) => { parentTaskFaulted = parentTask.IsFaulted; }, TaskContinuationOptions.OnlyOnFaulted); task.Start(); faultedTask.Wait(); Trace.Assert(parentTaskFaulted); if (!task.IsFaulted) { task.Wait(); } else { Console.WriteLine( "ERROR: {0}", task.Exception.Message); } }
void MainForm_Shown(object sender, EventArgs e) { this.MainForm.Shown -= MainForm_Shown; UpdateJumpList(); #if !DEBUG if (SingleInstance.IsFirstInstance(Assembly.GetEntryAssembly().FullName)) { _mgr = UpdateManager.GitHubUpdateManager("https://github.com/erdomke/InnovatorAdmin"); _mgr.ContinueWith(t => { var listener = this.MainForm as IUpdateListener; _updates = t.Result.UpdateApp(listener == null ? (Action<int>)null : listener.UpdateCheckProgress); _updates.ContinueWith(r => { if (r.IsFaulted) { Utils.HandleError(r.Exception); } else if (!r.IsCanceled && listener != null) { listener.UpdateCheckComplete(r.Result == default(ReleaseEntry) ? default(Version) : r.Result.Version.Version); } }); }); } #endif }
static void Main(string[] args) { Task<BankAccount> task = new Task<BankAccount>(() => { // create a new bank account BankAccount account = new BankAccount(); // enter a loop for (int i = 0; i < 1000; i++) { // increment the account total account.Balance++; } // return the bank account return account; }); task.ContinueWith((Task<BankAccount> antecedent) => { Console.WriteLine("Final Balance: {0}", antecedent.Result.Balance); }); // start the task task.Start(); // wait for input before exiting Console.WriteLine("Press enter to finish"); Console.ReadLine(); }
public DThread(Action action) { _task = new System.Threading.Tasks.Task(action, System.Threading.Tasks.TaskCreationOptions.LongRunning); _task.ContinueWith(_ => { _finishedEvent.Set(); }); }
public void ParticipateUntil (Task task) { ManualResetEventSlim evt = new ManualResetEventSlim (false); task.ContinueWith (_ => evt.Set (), TaskContinuationOptions.ExecuteSynchronously); ParticipateUntil (evt, -1); }
/// <summary>Transmits a packet.</summary> public Task<ReadonlySessionVariables> Transmit(CsspIdentity packet) { lock (this) { PreProcessPacket(packet); } var t = new Task<ReadonlySessionVariables>(() => { var session = CsGlobal.Transmission.Http.Secured.ClientSession(CsGlobal.Transmission.Http.CsServer.Rsa, CsGlobal.Transmission.Http.CsServer.Website); session.Request.Data = GetJson_FromPacket(packet); session.SendRequest(); return session.Response; }, TaskCreationOptions.LongRunning); var continuationTask = t.ContinueWith(t1 => { lock (this) { LastPacketTransmitted = DateTime.Now; PostProcessPacket(packet, t1.Exception == null); } return t1.Result; }, TaskScheduler.Default); t.Start(TaskScheduler.Default); return continuationTask; }
private void OnMikuniProtocol() { status = DialogManager.ShowStatus(this, Database.GetText("Communicating", "System")); Manager.LiveDataVector = Database.GetLiveData("QingQi"); for (int i = 0; i < Manager.LiveDataVector.Count; i++) { if ((Manager.LiveDataVector[i].ShortName == "TS") || (Manager.LiveDataVector[i].ShortName == "ERF") || (Manager.LiveDataVector[i].ShortName == "IS")) { Manager.LiveDataVector[i].Enabled = false; } } Core.LiveDataVector vec = Manager.LiveDataVector; vec.DeployEnabledIndex(); vec.DeployShowedIndex(); task = Task.Factory.StartNew(() => { if (!Manager.Commbox.Close() || !Manager.Commbox.Open()) { throw new IOException(Database.GetText("Open Commbox Fail", "System")); } Diag.MikuniOptions options = new Diag.MikuniOptions(); options.Parity = Diag.MikuniParity.Even; Mikuni protocol = new Mikuni(Manager.Commbox, options); protocol.StaticDataStream(vec); }); task.ContinueWith((t) => { ShowResult(t); }); }
/// <summary>父子任务 /// </summary> public static void M1() { Task<string[]> parent = new Task<string[]>(state => { Console.WriteLine(state); string[] result = new string[2]; //创建并启动子任务 new Task(() => { result[0] = "我是子任务1。"; }, TaskCreationOptions.AttachedToParent).Start(); new Task(() => { result[1] = "我是子任务2。"; }, TaskCreationOptions.AttachedToParent).Start(); return result; }, "我是父任务,并在我的处理过程中创建多个子任务,所有子任务完成以后我才会结束执行。"); //任务处理完成后执行的操作 parent.ContinueWith(t => { Array.ForEach(t.Result, r => Console.WriteLine(r)); }); //启动父任务 parent.Start(); }
// http://mnairooz.blogspot.com/2010/07/implementing-asynchronous-callbacks.html private void MainForm2_Load(object sender, EventArgs e) { var parent = new Task<int>(() => { MessageBox.Show(@"In parent"); return 100; }); Task<int> child = parent.ContinueWith( a => { MessageBox.Show(@"In Child"); return 19 + a.Result; }, TaskContinuationOptions.OnlyOnRanToCompletion); parent.Start(); Task.Factory.StartNew(() => { MessageBox.Show(@"In the lone parent..."); return "some"; }).ContinueWith(t => { MessageBox.Show(@"In the lone child"); label2.Text = string.Format("{0} data", t.Result.ToString(CultureInfo.InvariantCulture)); }, TaskScheduler.FromCurrentSynchronizationContext()); // MessageBox.Show(child.Result.ToString()); label1.Text = child.Result.ToString(CultureInfo.InvariantCulture); }
protected virtual void OnReload() { if (DisabledModIds == null || Reset) { DisabledModIds = new HashSet <string>(); Reset = false; } if (!PluginLoader.IsFirstLoadComplete) { return; // if the first load isn't complete, skip all of this } var referToState = unchecked (++updateState); var copy = DisabledModIds.ToArray(); if (disableUpdateTask == null || disableUpdateTask.IsCompleted) { disableUpdateTask = UpdateDisabledMods(copy); } else { disableUpdateTask = disableUpdateTask.ContinueWith(t => { // skip if another got here before the last finished if (referToState != updateState) { return(TaskEx.WhenAll()); } else { return(UpdateDisabledMods(copy)); } }); } }
public ConsultarCursosViewModel() { this.Periodos = new List<ConsultarPeriodosPeriodoDTO>(); var task = new Task(() => { Status = "Consultando Períodos..."; var modelPeriodos = new ConsultarPeriodosModel(); var requestPeriodos = new ConsultarPeriodosRequest(); modelPeriodos.Execute(requestPeriodos); if (modelPeriodos.Response.Status == ExecutionStatus.Success) this.Periodos = modelPeriodos.Response.Periodos; else System.Windows.Forms.MessageBox.Show(string.Concat("Erro ao consultar professores:\n",modelPeriodos.ErrorMessage)); Periodos.Add(new ConsultarPeriodosPeriodoDTO() { Codigo = 0, Nome = "<Nenhum>" }); Status = "Consultando Cursos..."; var modelCursos = new ConsultarCursosModel(); var requestCursos = new ConsultarCursosRequest(); modelCursos.Execute(requestCursos); if (modelCursos.Response.Status == ExecutionStatus.Success) this.Lista = modelCursos.Response.Cursos; else System.Windows.Forms.MessageBox.Show(string.Concat("Erro ao consultar professores:\n",modelCursos.ErrorMessage)); }); task.ContinueWith(x => { Status = ""; }); task.Start(); this.ActionCommand = new RelayCommand(); }
public static void Run() { //Task<int> t = Task.Run(() => TaskMethod() ); Task<int> t = new Task<int>(() => TaskMethod() ); t.Start(); /* try { // Even if continuation is added after the task // finishes execution, the continuation executes correctly. Console.WriteLine(t.Result); }catch(AggregateException e) { Console.WriteLine("Accessing result first throws exception."); } */ t.ContinueWith((task) => { Console.WriteLine("OK"); }, TaskContinuationOptions.OnlyOnRanToCompletion); Task contTask = t.ContinueWith((task) => { Console.WriteLine("ERROR"); throw new Exception("Continuation says piss off too"); }, TaskContinuationOptions.OnlyOnFaulted); try { Console.WriteLine(t.Result); }catch(AggregateException e) { Console.WriteLine("First task threw exception: " + e.InnerExceptions[0].Message); } try { contTask.Wait(); }catch(AggregateException e) { Console.WriteLine("Continuation threw exception: " + e.InnerExceptions[0].Message); } }
private static void IgnoreTaskErrors(System.Threading.Tasks.Task task) { task.ContinueWith(t => { var e = t.Exception; var log = ServiceContainer.Resolve <ILogger> (); log.Info(Tag, e, "Failed to send GCM info to server."); }, TaskContinuationOptions.OnlyOnFaulted); }
public static Task IgnoreCancellation(this Task task) { return(task.ContinueWith( t => { }, CancellationToken.None, TaskContinuationOptions.NotOnFaulted, TaskScheduler.Default)); }
private void SessionReceived(long taskId, Session session /*, int budget*/) { //ThreadPerTaskScheduler //System.Threading.Tasks.TaskFactory consumersFactory = new System.Threading.Tasks.TaskFactory(new System.Threading.Tasks.Schedulers.ThreadPerTaskScheduler()); if (chunkBuilderFeed.IsCompleted) { return; } System.Threading.Tasks.Task consumeTask = System.Threading.Tasks.Task.Factory.StartNew(() => { //Task consumeTask = consumersFactory.StartNew(() =>{ Consume(session); }, TaskCreationOptions.LongRunning); consumeTask.ContinueWith(o => AfterTask(consumeTask, session), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.NotOnFaulted | TaskContinuationOptions.NotOnCanceled); consumeTask.ContinueWith(o => UnexpectedError(consumeTask), TaskContinuationOptions.OnlyOnFaulted); //consumeTask.Dispose(); }
/// <summary> /// 投げっぱなしにする場合は、これを呼ぶことでコンパイラの警告の抑制と、例外発生時のロギングを行います。 /// </summary> public static void FireAndForget(this System.Threading.Tasks.Task task) { task.ContinueWith(x => { Debug.Write(x.Exception); //logger.ErrorException("TaskUnhandled", x.Exception); }, TaskContinuationOptions.OnlyOnFaulted); }
public FormWaiting(Task<Object> task) { WaitingForTask = task; WaitingForTask.ContinueWith(SafeClose); InitializeComponent(); timer.Tick += timer_Tick; lblWaiting.Tag = 0; }
private void Start() { // start the task that is doing the work currentWorkCycle = Work(); // chain a continuation that checks for more work, on the same scheduler currentWorkCycle.ContinueWith(t => this.CheckForMoreWork(), TaskScheduler.Current); }
public void Run() { Task taskData = new Task(GetData); taskData.Start(); // Producer Task taskProducer = taskData.ContinueWith(Producer); }
public static void DontWait(this System.Threading.Tasks.Task task) { task.ContinueWith(t => { if (t.Exception != null) { throw t.Exception; } }, TaskContinuationOptions.OnlyOnFaulted); }
private void RunBackup(Backup b) { this.Status = NodeStatus.Backuping; if (currentJobs.Count > 0) { // Refuse to process 2 simultaneous tasks on win XP since it can only handle 1 VSS snap at any given time. if (Utilities.PlatForm.Instance().OS == "NT5.1") { HubWrite(new NodeMessage { Context = MessageContext.Task, TaskId = b.Id, Data = "800" }); Logger.Append(Severity.WARNING, "A task is already running on Win-XP node, refusing to process other."); return; } foreach (BackupManager runningJob in currentJobs.Values) { if (runningJob.Backup.BackupSet.Id == b.BackupSetId) { HubWrite(new NodeMessage { Context = MessageContext.Task, TaskId = runningJob.Backup.Id, Data = "800" }); Logger.Append(Severity.WARNING, "Taskset #" + runningJob.Backup.BackupSetId + " (task id #" + runningJob.Backup.Id + ") " + runningJob.Backup.ToString() + " is already running, refusing to process it twice..."); return; } } } //backupsList.Add(b); Logger.Append(Severity.INFO, "Starting task +" + b.Id + ", operation Backup, type " + b.Level.ToString() + "."); b.HubNotificationEvent += this.HubSendTaskEvent; try{ System.Threading.Tasks.Task prepareTask = new System.Threading.Tasks.Task( () => { b.PrepareAll(); BackupManager bManager = new BackupManager(b); currentJobs.Add(b.Id, bManager); bManager.StorageNeeded += AskStorage; bManager.BackupDoneEvent += this.BackupDone; bManager.Run(); }, System.Threading.Tasks.TaskCreationOptions.LongRunning); prepareTask.Start(TaskScheduler.Default); // handle exceptions... prepareTask.ContinueWith( o => { UnexpectedError(prepareTask, b.Id); }, System.Threading.Tasks.TaskContinuationOptions.OnlyOnFaulted ); } catch (Exception e) { Logger.Append(Severity.ERROR, "<--> Interrupting task " + b.Id + " after unexpected error : " + e.ToString()); HubWrite("TSK " + b.Id + " 899 " + e.Message); BackupDone(b); } }
/// <summary> /// Executes the specified action on a background thread, showing a wait dialog if it is available /// </summary> /// <param name="actionName">[Required] description of the action to show in the wait dialog</param> /// <param name="action">[Required] action to run</param> /// <param name="throwOnCancel">If specified, an OperationCanceledException is thrown if the operation is canceled</param> /// <returns>True if the operation succeed and wasn't canceled</returns> /// <exception cref="OperationCanceledException">Wait was canceled and 'throwOnCancel' is true</exception> public static bool Wait(string actionName, bool throwOnCancel, Action action) { Task t = Task.Run(action); DebugEngineHost.HostWaitLoop waiterImpl = null; try { waiterImpl = new DebugEngineHost.HostWaitLoop(actionName); } catch (FileNotFoundException) { // Visual Studio is not installed on this box } if (waiterImpl != null) { using (ManualResetEvent completeEvent = new ManualResetEvent(false)) { CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); t.ContinueWith((System.Threading.Tasks.Task unused) => completeEvent.Set(), TaskContinuationOptions.ExecuteSynchronously); try { waiterImpl.Wait(completeEvent, cancellationTokenSource); } catch (OperationCanceledException) // VS Wait dialog implementation always throws on cancel { if (throwOnCancel) { throw; } return(false); } if (cancellationTokenSource.IsCancellationRequested) { if (throwOnCancel) { throw new OperationCanceledException(); } return(false); } if (t.IsFaulted) { throw t.Exception.InnerException; } } } return(true); }
private void SendIndex(long taskId, Session s /*, int budget*/) { System.Threading.Tasks.Task consumeIndexTask = System.Threading.Tasks.Task.Factory.StartNew(() => { DataPipeline pipeline = new DataPipeline(PipelineMode.Write, DataProcessingFlags.CCompress | DataProcessingFlags.CChecksum); //pipeline.Init(); ChunkProcessor cp = new ChunkProcessor(s, pipeline, backup); cp.Process(indexChunk, backup.MaxChunkSize * 10); indexChunk.Size = pipeline.Stream.Length; indexChunk.AddDestination(s.ClientId); }, TaskCreationOptions.LongRunning); consumeIndexTask.ContinueWith(o => { Logger.Append(Severity.INFO, "Processed and sent backup index"); backup.AddHubNotificationEvent(705, Math.Round((double)indexChunk.Size / 1024 / 1024, 1).ToString(), ""); string synthIndexSum = indexChunk.Sum; // for Fulls if (backup.Bs.ScheduleTimes[0].Level != P2PBackup.Common.BackupLevel.Full) { IndexManager idxManager = new IndexManager(); Logger.Append(Severity.INFO, "Building synthetic full index..."); idxManager.CreateSyntheticFullIndex(backup.RefTaskId, taskId, backup.RootDrives); backup.AddHubNotificationEvent(707, "", ""); synthIndexSum = IndexManager.CheckSumIndex(taskId, false); // for synthetic backups } User.SendDoneBackup(taskId, backup.OriginalSize, backup.FinalSize, backup.TotalItems, indexChunk.Name, indexChunk.Sum, synthIndexSum, indexChunk.StorageDestinations, 100); Logger.Append(Severity.INFO, "Task " + taskId + " has finished. " + backup.TotalItems + " items, " + backup.TotalChunks + " chunks. Original data size=" + Math.Round((double)backup.OriginalSize / 1024 / 1024, 1) + "MB, final=" + Math.Round((double)backup.FinalSize / 1024 / 1024, 1) + "MB"); string statsByKind = "Task " + taskId + " processed: "; for (int i = 0; i < 10; i++) { statsByKind += backup.ItemsByType[i] + " " + ((FileType)i).ToString() + ", "; } Logger.Append(Severity.INFO, statsByKind); #if DEBUG Logger.Append(Severity.INFO, "DataProcessorStreams statistics : checksum=" + BenchmarkStats.Instance().ChecksumTime + "ms, dedup=" + BenchmarkStats.Instance().DedupTime + "ms, compress=" + BenchmarkStats.Instance().CompressTime + "ms, send=" + BenchmarkStats.Instance().SendTime + "ms."); Logger.Append(Severity.INFO, "Dedup statistics : lookups=" + BenchmarkStats.Instance().DedupLookups + ", hotfound=" + BenchmarkStats.Instance().DedupHotFound + ", coldfound=" + BenchmarkStats.Instance().DedupColdFound + ", add=" + BenchmarkStats.Instance().DedupAdd + "."); #endif User.StorageSessionReceivedEvent -= new User.StorageSessionReceivedHandler(this.SendIndex); //Console.WriteLine("IndexSessionReceived() : backup typre="+backup. .BackupTimes[0].Type); backup.AddHubNotificationEvent(706, "", ""); backup.Terminate(true); BackupDoneEvent(taskId); }, TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.NotOnFaulted | TaskContinuationOptions.NotOnCanceled); //consumeTask.Dispose(); }
/// <summary> /// Silently handles the specified exception. /// </summary> public static Task SilenceException <T>(this Task task) where T : Exception { return(task.ContinueWith(t => { try { t.Wait(); } catch (AggregateException ex) { ex.Handle(e => e is T); } })); }
private void btnTaskContinuationsRun_Click(object sender, EventArgs e) {//任务调度也是常见的需求,Task支持一个任务结束之后执行另一个任务。 System.Threading.Tasks.Task task1 = System.Threading.Tasks.Task.Factory.StartNew(() => Console.Write("antecedant..")); System.Threading.Tasks.Task task2 = task1.ContinueWith(task => Console.Write("..continuation")); //Task也有带返回值的重载,示例代码如下: System.Threading.Tasks.Task.Factory.StartNew <int>(() => 8) .ContinueWith(ant => ant.Result * 2) .ContinueWith(ant => Math.Sqrt(ant.Result)) .ContinueWith(ant => Console.WriteLine(ant.Result)); // output 4 }
/// <summary> /// Silently handles the specified exception. /// </summary> public static Task <U> SilenceException <T, U>(this Task <U> task) where T : Exception { return(task.ContinueWith(t => { try { return t.Result; } catch (AggregateException ex) { ex.Handle(e => e is T); return default(U); } })); }
// Start a fetch request. public void FetchData() { DebugLog("Fetching data..."); // FetchAsync only fetches new data if the current data is older than the provided // timespan. Otherwise it assumes the data is "recent enough", and does nothing. // By default the timespan is 12 hours, and for production apps, this is a good // number. For this example though, it's set to a timespan of zero, so that // changes in the console will always show up immediately. System.Threading.Tasks.Task fetchTask = Firebase.RemoteConfig.FirebaseRemoteConfig.FetchAsync( TimeSpan.Zero); fetchTask.ContinueWith(FetchComplete); }
internal void SessionReceived(Session session /*, int budget*/) { if (chunksFeeds.IsCompleted) { return; // TODO : verify that in this case, session is closed. } /*if(chunksFeeds.IsCompleted){ * SendIndex(session); * }*/ else { System.Threading.Tasks.Task consumeTask = System.Threading.Tasks.Task.Factory.StartNew(() => { Consume(session); } /*, null, TaskCreationOptions.LongRunning, TaskScheduler.Default*/); consumeTask.ContinueWith(o => AfterTask(consumeTask, session), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.NotOnFaulted | TaskContinuationOptions.NotOnCanceled); consumeTask.ContinueWith(o => UnexpectedError(consumeTask), TaskContinuationOptions.OnlyOnFaulted); consumeTask.ContinueWith(o => Cancel(), TaskContinuationOptions.OnlyOnCanceled); consumers.Add(consumeTask); } }
internal void SendIndex(Session s) { // Terminate and free Dedup DB before saving it to ensure all its content has been flushed to disk dedupIndex.Dispose(); System.Threading.Tasks.Task consumeIndexTask = System.Threading.Tasks.Task.Factory.StartNew(() => { DataPipeline pipeline = new DataPipeline(PipelineMode.Write, DataProcessingFlags.CCompress | DataProcessingFlags.CChecksum); ChunkProcessor cp = new ChunkProcessor(s, pipeline, backup, new CancellationToken()); cp.Process(indexChunk, backup.BackupSet.MaxChunkSize * 10); indexChunk.Size = pipeline.Stream.Length; indexChunk.AddDestination(s.ToNode.Id); }, TaskCreationOptions.LongRunning); consumeIndexTask.ContinueWith(o => { Logger.Append(Severity.INFO, "Processed and sent backup index"); backup.AddHubNotificationEvent(705, Math.Round((double)indexChunk.Size / 1024 / 1024, 1).ToString(), ""); // set final info : index location backup.IndexStorageNodes = indexChunk.StorageDestinations; Logger.Append(Severity.INFO, "Task " + s.TaskId + " has finished. " + backup.TotalItems + " items, " + backup.TotalChunks + " chunks. Original data size=" + Math.Round((double)backup.OriginalSize / 1024 / 1024, 1) + "MB, final=" + Math.Round((double)backup.FinalSize / 1024 / 1024, 1) + "MB"); string statsByKind = "Task " + s.TaskId + " processed: "; for (int i = 0; i < 10; i++) { statsByKind += backup.ItemsByType[i] + " " + ((FileType)i).ToString() + ", "; } Logger.Append(Severity.INFO, statsByKind); #if DEBUG Logger.Append(Severity.INFO, "DataProcessorStreams statistics : checksum=" + BenchmarkStats.Instance().ChecksumTime + "ms, dedup=" + BenchmarkStats.Instance().DedupTime + "ms, compress=" + BenchmarkStats.Instance().CompressTime + "ms, send=" + BenchmarkStats.Instance().SendTime + "ms."); Logger.Append(Severity.INFO, "Dedup statistics : lookups=" + BenchmarkStats.Instance().DedupLookups + ", hotfound=" + BenchmarkStats.Instance().DedupHotFound + ", coldfound=" + BenchmarkStats.Instance().DedupColdFound + ", add=" + BenchmarkStats.Instance().DedupAdd + "."); #endif //User.SessionReady -= new User.StorageSessionReceivedHandler(this.SendIndex); backup.AddHubNotificationEvent(706, "", ""); backup.Terminate(true); BackupDoneEvent(backup); }, TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.NotOnFaulted | TaskContinuationOptions.NotOnCanceled ); //consumeTask.Dispose(); }
protected Task ParseMedicationsAsync(Task <Bundle> result) { return(result.ContinueWith(bund => { Task.Run(() => //This is not necessary for such a small dataset but if this was very large it could help because this is a CPU bound process Task.Run is appropriate. { MedsToChannel(bund.GetAwaiter().GetResult().Entry .Select(e => e.Resource as Bundle) .SelectMany(b => b.Entry .Select(e => e.Resource)) .ToList()); }); })); }
private void StartUpdateStateMachine() { // cancel previous state machine update request _cancellationTokenSource.Cancel(); _cancellationTokenSource = new CancellationTokenSource(); var cancellationToken = _cancellationTokenSource.Token; // make sure all state machine change work is serialized so that cancellation // doesn't mess the state up. _lastTask = _lastTask.ContinueWith(async _ => { await UpdateStateMachineWorkerAsync(cancellationToken).ConfigureAwait(false); }, cancellationToken, TaskContinuationOptions.LazyCancellation, TaskScheduler.Default).Unwrap(); }
Task FetchDataAsync() { if (!mInited || mIsLoading || mLastLoadTime + 12 * 60 * 60 > AFramework.Utility.GetCurrentTimeSecond()) { return(null); } mIsLoading = true; System.Threading.Tasks.Task fetchTask = Firebase.RemoteConfig.FirebaseRemoteConfig.FetchAsync( #if DEVELOPMENT_BUILD System.TimeSpan.Zero #endif ); return(fetchTask.ContinueWith(FetchComplete)); }
/// <summary> /// ReferencesGraphProvider supports tracking changes. /// ProjectContextChanged gets fired everytime dependencies change. TrackChangesAsync updates /// ExpandedGraphContexts as necessary to reflect changes. /// </summary> private void ProjectContextProvider_ProjectContextChanged(object sender, ProjectContextEventArgs e) { lock (_changedContextsQueueLock) { _changedContextsQueue[e.Context.ProjectFilePath] = e; // schedule new track changes request in the queue if (_trackChangesTask == null || _trackChangesTask.IsCompleted) { _trackChangesTask = RunTrackChangesAsync(); } else { _trackChangesTask = _trackChangesTask.ContinueWith(t => RunTrackChangesAsync(), TaskScheduler.Default); } } }
private void Export_Click(object sender, RoutedEventArgs e) { //State = State.Busy; //wait.Message = "Пожалуйста, подождите..\nПодготовка отчёта..."; var task = new System.Threading.Tasks.Task(() => { var reportFileName = System.IO.Path.Combine(System.IO.Path.GetTempPath(), _balance.Substation.Name + ".xlsx"); int index = 0; while (System.IO.File.Exists(reportFileName) == true) { try { System.IO.File.Delete(reportFileName); } catch (System.IO.IOException) { reportFileName = System.IO.Path.Combine(System.IO.Path.GetTempPath(), _balance.Substation.Name + " " + ++index + ".xlsx"); } } using (var sbe = new Export.SubstationExport(_balance)) sbe.Export(reportFileName); System.Diagnostics.Process.Start(reportFileName); //State = State.Idle; //DispatcherExtensions.InUi(() => wait.Message = "Пожалуйста, подождите..\nПодготовка данных."); }, System.Threading.Tasks.TaskCreationOptions.AttachedToParent); task.ContinueWith((s) => { var sb = new System.Text.StringBuilder(); Exception ex = s.Exception.Flatten(); while (ex != null) { if (ex.InnerException != null) { sb.AppendLine(ex.InnerException.Message); ex = ex.InnerException; } } EmcosSiteWrapperApp.LogError("Экспорт балансов подстанций - ошибка: " + sb.ToString()); DispatcherExtensions.InUi(() => EmcosSiteWrapperApp.ShowError("Произошла ошибка при формировании отчёта.\nОбратитесь к разработчику.")); }, System.Threading.Tasks.TaskContinuationOptions.OnlyOnFaulted); task.Start(System.Threading.Tasks.TaskScheduler.Current); }
public static void DisconnectClient(Client client, string reason) { if (client.WebSocket.IsAvailable) { string msg = "{\"identifier\":\"" + "error" + "\",\"param\":\"" + reason + "\"}\n"; System.Threading.Tasks.Task t = client.WebSocket.Send(msg); t.ContinueWith((prevTask) => { prevTask.Wait(); RemoveClient(client.WebSocket.ConnectionInfo.Id); }); } else { RemoveClient(client.WebSocket.ConnectionInfo.Id); } }