private static void CallerWithAwaiter() { TraceThreadAndTask($"starting{nameof(CallerWithAwaiter)}"); TaskAwaiter <string> awaiter = GreetingAsync("Matthias").GetAwaiter(); awaiter.OnCompleted(OnCompleteAwaiter); void OnCompleteAwaiter() { Console.WriteLine(awaiter.GetResult()); TraceThreadAndTask($"ended{nameof(CallerWithAwaiter)}"); } }
//https://www.cnblogs.com/qiandi/p/4704255.html void Start() { //Task ~~ Coroutine //Await ~~ yield return //Async ~~ IEnumerator Task.Run(delegate() { Thread.Sleep(1000); print("当前线程id " + Thread.CurrentThread.ManagedThreadId); }); print("当前线程id " + Thread.CurrentThread.ManagedThreadId); Task task1 = new Task(new Action(Test1)); //用法二 Task task2 = new Task(delegate { Test1(); }); //用法三 Task task3 = new Task(() => Test1()); Task task4 = new Task(() => { Test1(); }); task1.Start(); task2.Start(); task3.Start(); task4.Start(); Task.Run(async delegate() { int count = await Test5(); print("TaskCompletionSource 结果是 :" + count); }); Task task = Task.Run(delegate() { Debug.Log("我正在执行任务的线程id" + Thread.CurrentThread.ManagedThreadId); Thread.Sleep(5); }); TaskAwaiter awaiter = task.GetAwaiter(); awaiter.OnCompleted(delegate() { Debug.Log("我完成了的回调任务的线程id" + Thread.CurrentThread.ManagedThreadId); }); //print("最后结尾"); }
/// <summary> /// 使用Awaiter /// </summary> /// <param name="name"></param> private static void GetSelfAwaiter(string name) { SeeThreadAndTask($"运行{nameof(GetSelfAwaiter)}"); TaskAwaiter <string> awaiter = GetStringAsync(name).GetAwaiter(); awaiter.OnCompleted(OnCompletedAwauter); void OnCompletedAwauter() { Console.WriteLine(awaiter.GetResult()); SeeThreadAndTask($"运行{nameof(GetSelfAwaiter)}"); } }
public void MoveNext() { switch (state) { case 0: goto firstState; case 1: goto secondState; case 2: goto thirdState; } firstState: Console.WriteLine("Starting clock"); goto secondAndHalfState; secondState: awaiter.GetResult(); secondAndHalfState: Console.Write("Tick"); awaiter = Task.Delay(500).GetAwaiter(); if (!awaiter.IsCompleted) { state = 2; awaiter.OnCompleted(MoveNext); return; } thirdState: awaiter.GetResult(); Console.WriteLine("Tock"); if (!awaiter.IsCompleted) { state = 1; awaiter.OnCompleted(MoveNext); return; } goto secondState; }
static void Main(string[] args) { // perform awaited call TaskAwaiter <int> aw = AsyncFunction().GetAwaiter(); aw.OnCompleted(() => { int result = aw.GetResult(); }); // perform unawaited call AsyncFunction2(); }
public static void Main() { Task <int> t = Task.Run(() => Sum(1000)); t.ContinueWith(task => Console.WriteLine($"ContinueWith : {task.Result}")); TaskAwaiter <int> awaiter = t.GetAwaiter(); awaiter.OnCompleted(() => Console.WriteLine($"awaiter : {awaiter.GetResult()}")); Console.ReadLine(); }
/// <summary> /// 添加监视任务 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="task">线程任务委托</param> /// <param name="onException">异常处理委托</param> /// <param name="callerFilePath">调用文件路径</param> /// <param name="callerLineNumber">所在文件行数</param> /// <param name="callerMemberName">调用成员名称</param> public static void Add <T>(Task <T> task, Action <AggregateException> onException = null, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNumber = 0, [CallerMemberName] string callerMemberName = null) { TaskAwaiter <T> taskAwaiter = task.GetAwaiter(); if (taskAwaiter.IsCompleted) { checkException(task.Exception, onException); } else { CatchTask <T> catchTask = new CatchTask <T>(onException, callerFilePath ?? string.Empty, callerLineNumber, callerMemberName ?? string.Empty, task); taskAwaiter.OnCompleted(catchTask.OnCompleted); } }
public void GetWindows() { if (fresh || getWindowsAwaiter.IsCompleted) { getWindowsAwaiter = Task.Run(() => { Finder.GetWindows(); }).GetAwaiter(); getWindowsAwaiter.OnCompleted(() => { refreshList(); }); fresh = false; } }
void IAsyncStateMachine.MoveNext() { Console.WriteLine("+"); task = new Task(Operation); // 1. Создание задачи taskAwaiter = task.GetAwaiter(); // 2. Создание "ожидателя" taskAwaiter.OnCompleted(Continuation); // taskAwaiter.UnsafeOnCompleted(Continuation); task.Start(); if (!taskAwaiter.IsCompleted) // 3. Задача выполняется - следовательно заходим в тело if { builder.AwaitUnsafeOnCompleted(ref taskAwaiter, ref this); //builder.AwaitOnCompleted(ref taskAwaiter, ref this); //AwaitOnCompleted(ref taskAwaiter, ref this); } }
/// <summary> /// Implementing the same logic as the async/await method /// but using awaiters /// </summary> public void MethodOneAwaiter() { Task task = DoWorkAsync(); TaskAwaiter awaiter = task.GetAwaiter(); awaiter.OnCompleted(() => { try { awaiter.GetResult(); } catch (ArgumentException e) { } }); }
/// <summary> /// 任务完成检测 /// </summary> internal void OnCompleted() { TaskAwaiter TaskAwaiter = task.GetAwaiter(); if (TaskAwaiter.IsCompleted) { if (TaskLink.PopNotNull(this)) { checkException(task.Exception, onException); } } else { TaskAwaiter.OnCompleted(OnCompleted); } }
//使用Awaiter public static void CallerWithAwaiter() { TraceThreadAndTask($"started {nameof(CallerWithAwaiter)}"); //GetAwaiter返回一个TaskAwaiter //可以对任何提供GetAwaiter方法的对象使用async关键字 TaskAwaiter <string> awaiter = GreetingAsync("Jacl").GetAwaiter(); //使用OnCompletet方法实现INotifyCompletion接口 //此方法在任务完成时调用,这里就是在任务完成时调用OnCompleteAwaiter本地方法 awaiter.OnCompleted(OnCompleteAwaiter); //本地函数 void OnCompleteAwaiter() { Console.WriteLine(awaiter.GetResult()); TraceThreadAndTask($"ended {nameof(CallerWithAwaiter)}"); } }
private static void CleanUpTask(TaskAwaiter taskAwaiter) { taskAwaiter.OnCompleted(() => { Console.WriteLine(); var consoleBackground = Console.BackgroundColor; var consoleForeground = Console.ForegroundColor; Console.BackgroundColor = ConsoleColor.Red; if (p.cancel.IsCancellationRequested) { Console.WriteLine($"Task [{p.task.Id}] cancellation requested."); } Console.WriteLine($"Task [{p.task.Id}] canceled/completed: {p.task?.IsCanceled}/{p.task?.IsCompleted}"); Console.BackgroundColor = consoleBackground; }); }
private void Print() { for (int i = 0; i < 5; i++) { TaskAwaiter <int> awaiter = GetPrimesCountAsync(i * 1000000 + 2, 1000000) .GetAwaiter(); awaiter.OnCompleted(() => { Console.Write( $"{awaiter.GetResult()} primes between ... and ...");//这里已经拿不到i了,前面内存共享讲过了 Console.Write($" {DateTime.Now.ToLongTimeString()}\r\n"); }); } Console.WriteLine($"Print循环完成:{DateTime.Now.ToLongTimeString()}"); }
static void Main1() { Task <int> task = Task.Run(() => { //do some thing return(1); }); TaskAwaiter <int> taskAwaiter = task.GetAwaiter(); taskAwaiter.OnCompleted(() => { int result = taskAwaiter.GetResult(); Console.WriteLine(result); }); Console.ReadLine(); }
public void Run3() { Task <int> task = Task.Run <int> ( () => Enumerable.Range(0, 10000).Sum(x => x) ); TaskAwaiter <int> awaiter = task.GetAwaiter(); awaiter.OnCompleted(() => { // Task任務結束後,會直接跑這段程式碼 var sum = awaiter.GetResult(); Console.WriteLine("接續作業取值:{0}", sum); }); Console.WriteLine("程式執行中...."); Console.WriteLine("取得結果:{0}", task.Result); // 使用接續作業,不影響其他地方取得Result屬性 }
private void DoWorkTask() { //using lamda expression instead of Action delegate. //Task task = Task.Factory.StartNew(()=>BackGroundTask4(this)); //using Action delegate Task task = Task.Factory.StartNew(new Action <object>(BackGroundTask4), this); this.Output = this.Output + "\r\n" + GetThreadID() + "DoWorkTask Completed Before"; TaskAwaiter awaiter = task.GetAwaiter(); awaiter.OnCompleted( () => { this.Output = this.Output + "\r\n" + GetThreadID() + "DoWorkTask Completed."; } ); this.Output = this.Output + "\r\n" + GetThreadID() + "DoWorkTask Completed After"; }
public void Run() { Task <int> task = Task.Run(Go); TaskAwaiter <int> taskAwaiter = task.GetAwaiter(); //告诉先导任务执行完毕后,接着执行这里的委托: taskAwaiter.OnCompleted(() => { int result = taskAwaiter.GetResult(); //int result = task.Result;//两种获取任务执行结果的方法都行,这里可能会捕捉到先导任务的异常(不是包装后的AggregateException,而是原始异常,因为当前代码就处于先导任务的线程中) Console.WriteLine(result); Console.WriteLine($"OnCompleted线程:{Thread.CurrentThread.ManagedThreadId}"); }); Console.WriteLine("Done"); }
/// <summary> /// If the TabbedParent has a CurrentArrangement value, load the form with these values /// </summary> /// <param name="tabParent"></param> public ArrangementPage(TabbedArrangementPage tabParent) { InitializeComponent(); arrangementList = new List <GetSimpleArrangementResponse>(); foreach (GetSimpleArrangementResponse ar in arrangementList) { arrangementListOC.Add(ar); } ArrangementListView.ItemsSource = arrangementListOC; GetUsers(); ObservableCollection <KeyValuePair <long, string> > list2 = new ObservableCollection <KeyValuePair <long, string> >(); list2.Add(new KeyValuePair <long, string>(1, "180")); list2.Add(new KeyValuePair <long, string>(2, "360")); Style.ItemsSource = list2; containers.Add(new KeyValuePair <long, string>(1, "New container")); Container.ItemsSource = containers; EnableCustomerContainerSecondaryControls(false); TabParent = tabParent; GiftCheckBox.IsChecked = false; ArrangementListView.ItemsSource = new ObservableCollection <WorkOrderViewModel>(); ArrangementListView.ItemSelected += ArrangementListView_ItemSelected; TaskAwaiter t = ((App)App.Current).GetCustomerContainers(TabParent.Customer.Person.person_id).ContinueWith(a => CustomerContainersLoaded(a.Result)).GetAwaiter(); t.OnCompleted(() => { CompleteInitialization(); }); }
private void ButtonStartTaskTAPClick(object sender, EventArgs e) { //https://msdn.microsoft.com/en-us/library/hh873177(v=vs.110).aspx string methodName = $"{MethodBase.GetCurrentMethod().Name}()"; WriteToLog($"{methodName} starting..."); Task <int> task = TaskTAP(new TaskParam(0, GetValue(tbmSec, MSec))); TaskAwaiter <int> awaiter = task.GetAwaiter(); awaiter.OnCompleted(() => { int result = awaiter.GetResult(); WriteToLog($"{methodName} result = {result}"); }); WriteToLog($"{methodName} finished task.Status = {task.Status}"); }
public void DisplayPrimesCountFrom(int i) { TaskAwaiter <int> awaiter = GetPrimesCountAsync(i * 1000 + 2, 1000).GetAwaiter(); awaiter.OnCompleted(() => { awaiter.GetResult(); if (i++ < 10) { DisplayPrimesCountFrom(i); // рекрсивный вызов метода при необходимости продолжения // таким образом обеспечивается последовательное выполнение задач. } else { Console.WriteLine("Done"); src.SetResult(null); // закончили, отправляем результат из конечного автомата. } }); }
//如果方法不适用async修饰符,而需要返回ValueTask //可以使用传递结果或者传递Task对象的构造函数创建ValueTask对象 static ValueTask <string> GreetingValueTask2Async(string name) { if (names.TryGetValue(name, out string result)) { return(new ValueTask <string>(result)); //方法没Async,直接用构造函数转成ValueTask } else { Task <string> t1 = GreetingAsync(name); TaskAwaiter <string> awaiter = t1.GetAwaiter(); awaiter.OnCompleted(OnCompletion); //Task执行的回调 return(new ValueTask <string>(t1)); //用ValueTask构造函数转Task void OnCompletion() { names.Add(name, awaiter.GetResult()); } } }
static Task <string> GreetingValueTask2Async(string name) { if (names.TryGetValue(name, out string result)) { return(new Task <string>(result)); } else { Task <string> t1 = GreetingAsync(name); TaskAwaiter <string> awaiter = t1.GetAwaiter(); awaiter.OnCompleted(OnCompletion); return(new Task <string>(t1)); void OnCompletion() { names.Add(name, awaiter.GetResult()); } } }
public void PrintFrom(int i, int times) { TaskAwaiter <int> awaiter = GetPrimesCountAsync(i * 1000000 + 2, 1000000) .GetAwaiter(); awaiter.OnCompleted(() => { Console.WriteLine( $"{awaiter.GetResult()} primes between ... and ..."); if (++i < times) { PrintFrom(i, times); } else { Console.WriteLine($"Print结束:{DateTime.Now.ToLongTimeString()}\r\n"); } }); }
private Task PrintAnswerToLife2() { var taskCompletionSource = new TaskCompletionSource <object>(); TaskAwaiter awaiter = Task.Delay(5000).GetAwaiter(); awaiter.OnCompleted(() => { try { awaiter.GetResult(); int answer = "TheAnswerToLifeTheUniverseAndEverythingIs".Length; Console.WriteLine(answer); taskCompletionSource.SetResult(null); } catch (Exception ex) { taskCompletionSource.SetException(ex); } }); return(taskCompletionSource.Task); }
public static void TestContinuationWithAwaiter() { Task <int> t = Task.Run(() => { throw null; // кидаем эксепшен return(0); }, CancellationToken.None); TaskAwaiter <int> awaiter = t.GetAwaiter(); awaiter.OnCompleted(() => { try { int result = awaiter.GetResult(); // тут эксепшен будет переброшен } catch (Exception e) { Console.WriteLine(e.GetType()); // не оборачивается в AggregateException!! } }); Console.Read(); }
/// <summary> /// Initializes a new instance of the <see cref="WebSocketTask"/> class. /// </summary> /// <param name="task">The task.</param> /// <param name="tokenSource">The token source.</param> /// <exception cref="ArgumentNullException"> /// task - task cannot be null. /// or /// tokenSource - tokenSource cannot be null. /// </exception> public WebSocketTask(Task task, CancellationTokenSource tokenSource) : this() { if (task == null) { throw new ArgumentNullException("task", "task cannot be null."); } else if (tokenSource == null) { throw new ArgumentNullException("tokenSource", "tokenSource cannot be null."); } this.task = task; this.tokenSource = tokenSource; if (task.IsCanceled || task.IsCompleted || task.IsFaulted) { Dispose(); } TaskAwaiter tw = task.GetAwaiter(); tw.OnCompleted(HandleCompletion); }
static void process(ImageProcess imageProcess) { string urlPath = null; if (imageProcess.ImageTypeId == Enums.ImageTypes.Product) { urlPath = Path.Combine(Stc.ImageSourceUrl, "product"); } else if (imageProcess.ImageTypeId == Enums.ImageTypes.Profile) { urlPath = Path.Combine(Stc.ImageSourceUrl, "profile"); } string fileName = Path.Combine(urlPath, imageProcess.StoreTypeId == StoreType.Normal ? "" : "thumbnail", imageProcess.UniqueId.ToString().ToUpper() + "." + imageProcess.FileTypeId.ToString()); var source = Tinify.FromFile(fileName); TaskAwaiter taskAwaiter = source.ToFile(fileName).GetAwaiter(); taskAwaiter.OnCompleted(() => done(imageProcess) ); }
private static void Test01_Asynchrone() { Console.WriteLine("Lancement d'une fonction longue asynchrone"); int i = 0; Task <double> task = TimeConsumingFunctionAsync(); TaskAwaiter <double> awaiter = task.GetAwaiter(); awaiter.OnCompleted( () => { i = 20; double resultat2 = awaiter.GetResult(); Console.Write("Résultat: "); Console.WriteLine(resultat2); } ); for (i = 1; i < 15; i++) { Console.WriteLine(i); Thread.Sleep(1000); } /* * Lancement d'une fonction longue asynchrone * 1 * 2 * 3 * 4 * 5 * 6 * Résultat: -24,4605663988507 * */ }
private static void GetTaskResultViaAwaiter() { if (SynchronizationContext.Current != null) { SynchronizationContext.Current.ToString(); } Task <int> t = Task.Run(code); TaskAwaiter <int> awaiter = t.GetAwaiter(); try { awaiter.OnCompleted(() => { try { int result = awaiter.GetResult(); Console.WriteLine(result); } catch (ArgumentException ex) { Console.WriteLine(ex.GetType()); Console.Read(); } catch (Exception e) { e.ToString(); } //throw new ApplicationException(result.ToString()); }); } catch (ApplicationException n) { // i am not getting here Console.WriteLine(n.GetType()); } }
public void MoveNext() { int result; try { #pragma warning disable 0219 // doFinallyBodies is never used bool doFinallyBodies = true; #pragma warning restore if (state != 1) { if (state != -1) { task = Task<int>.Factory.StartNew(() => 5); awaiter = task.GetAwaiter(); if (awaiter.IsCompleted) { goto Label_GetResult; } state = 1; doFinallyBodies = false; awaiter.OnCompleted(moveNextDelegate); } return; } state = 0; Label_GetResult: // target of state=1 int awaitResult = awaiter.GetResult(); awaiter = default(TaskAwaiter<int>); result = awaitResult; } catch (Exception e) { state = -1; builder.SetException(e); return; } state = -1; builder.SetResult(result); }
public void MoveNext() { int result; try { bool doFinallyBodies = true; int tmpState = state; // Effectively a three way switch: 1, -1, 0 if (tmpState != 1) { if (state == -1) { return; } this.writer = File.CreateText("output.txt"); } try { tmpState = state; if (tmpState == 1) { goto Label_ResumePoint; } sum = 0; i = 0; Label_ResumePoint: // This shouldn't quite be here... see below while (i < loopCount) { // Not in generated code: if (state == 1) { goto Label_ResumePoint2; } // Back to generated code valueFetcher = Task.Factory.StartNew(() => 1); j = 0; // Still not in the generated code, and still not quite right... we don't want the j test here Label_ResumePoint2: // Back to generated code again... while (j < 3) { try { // We want Label_ResumePoint to be here really tmpState = state; if (tmpState != 1) { Console.WriteLine("Awaiting..."); awaiter = valueFetcher.GetAwaiter(); if (!awaiter.IsCompleted) { state = 1; doFinallyBodies = false; awaiter.OnCompleted(moveNextDelegate); return; } } else { state = 0; } int awaitResult = awaiter.GetResult(); awaiter = new TaskAwaiter<int>(); value = awaitResult; writer.WriteLine("Got value {0}", value); sum += value; break; } catch (Exception) { Console.WriteLine("Oops... retrying"); } j++; } i++; } result = sum; } finally { if (doFinallyBodies && writer != null) { writer.Dispose(); } } } catch (Exception e) { state = -1; builder.SetException(e); return; } state = -1; builder.SetResult(result); }
public void MoveNext() { int result; try { #pragma warning disable 0219 // doFinallyBodies is never used bool doFinallyBodies = true; #pragma warning restore switch (state) { case 1: break; case 2: goto Label_Awaiter2Continuation; case 3: goto Label_Awaiter3Continuation; default: if (state != -1) { task1 = Task.Factory.StartNew(() => 1); task2 = Task.Factory.StartNew(() => 2); task3 = Task.Factory.StartNew(() => 3); awaiter1 = task1.GetAwaiter(); if (awaiter1.IsCompleted) { goto Label_GetAwaiter1Result; } state = 1; doFinallyBodies = false; awaiter1.OnCompleted(moveNextDelegate); } return; } state = 0; Label_GetAwaiter1Result: int awaitResult1 = awaiter1.GetResult(); awaiter1 = new TaskAwaiter<int>(); value1 = awaitResult1; awaiter2 = task2.GetAwaiter(); if (awaiter2.IsCompleted) { goto Label_GetAwaiter2Result; } state = 2; doFinallyBodies = false; awaiter2.OnCompleted(moveNextDelegate); return; Label_Awaiter2Continuation: state = 0; Label_GetAwaiter2Result: int awaitResult2 = awaiter2.GetResult(); awaiter2 = new TaskAwaiter<int>(); value2 = awaitResult2; awaiter3 = task3.GetAwaiter(); if (awaiter3.IsCompleted) { goto Label_GetAwaiter3Result; } state = 3; doFinallyBodies = false; awaiter3.OnCompleted(moveNextDelegate); return; Label_Awaiter3Continuation: state = 0; Label_GetAwaiter3Result: int awaitResult3 = awaiter3.GetResult(); awaiter3 = new TaskAwaiter<int>(); value3 = awaitResult3; result = value1 + value2 + value3; } catch (Exception e) { state = -1; builder.SetException(e); return; } state = -1; builder.SetResult(result); }