private Task <bool> Display_Internal(int height, int width, Func <Form, bool?> onClosing = null, Action <Form> onDisplay = null, bool isDialog = false) { var promise = new System.Threading.Tasks.TaskCompletionSource <bool>(); win.Height = height; win.Width = width; win.Content = this.Host; win.Closing += (_sender, _args) => { log.Debug("Window is closing"); /* * _args.Cancel = true => stops the window from closing + So what we do if they didn't specif an onClosing, is we set cancel to false */ _args.Cancel = onClosing?.Invoke(this) ?? false; if (_args.Cancel == false && promise.Task.IsCompleted == false) { promise.SetResult(true); // window is closed } }; onDisplay?.Invoke(this); // showing the form, so notify people if they wanted notification if (isDialog) { if (parentForm != null) { parentForm._Internal_ShowDialog(win) .ContinueWith(t => { if (!promise.Task.IsCompleted) { promise.SetResult(true); } }); } else { throw new Exception( "Cannot show window as ShowDialog unless you have a parent form. parentForm was null"); } } else { win.Show(); } return(promise.Task); }
static System.Threading.Tasks.Task Delay(int milliseconds) { var tcs = new System.Threading.Tasks.TaskCompletionSource <object>(); new System.Threading.Timer(_ => tcs.SetResult(null)).Change(milliseconds, -1); return(tcs.Task); }
private static Task HandleOverlayOnHide(MetroDialogSettings settings, MetroWindow window) { Task result = null; if (!window.metroActiveDialogContainer.Children.OfType <BaseMetroDialog>().Any()) { result = (settings == null || settings.AnimateHide ? window.HideOverlayAsync() : Task.Factory.StartNew(() => window.Dispatcher.Invoke(new Action(window.HideOverlay)))); } else { var tcs = new System.Threading.Tasks.TaskCompletionSource <object>(); tcs.SetResult(null); result = tcs.Task; } result.ContinueWith(task => { window.Invoke(() => { if (window.metroActiveDialogContainer.Children.Count == 0) { window.SetValue(MetroWindow.IsCloseButtonEnabledWithDialogPropertyKey, BooleanBoxes.TrueBox); window.RestoreFocus(); } else { var onTopShownDialogSettings = window.metroActiveDialogContainer.Children.OfType <BaseMetroDialog>().LastOrDefault()?.DialogSettings; var isCloseButtonEnabled = window.ShowDialogsOverTitleBar || onTopShownDialogSettings == null || onTopShownDialogSettings.OwnerCanCloseWithDialog; window.SetValue(MetroWindow.IsCloseButtonEnabledWithDialogPropertyKey, BooleanBoxes.Box(isCloseButtonEnabled)); } }); }); return(result); }
// Parallelized merge sort algorithm. Uses Task infrastructure to spread sort across available resources private static async Task ParallelSort(TDataStructure arrayToSort, int index, int length, TComparer comparer) { if (length < ParallelSortThreshold) { SequentialSort(arrayToSort, index, length, comparer); } else { TDataStructureAccessor accessor = default(TDataStructureAccessor); int halfLen = length / 2; TaskCompletionSource <bool> rightSortComplete = new System.Threading.Tasks.TaskCompletionSource <bool>(); _ = Task.Run(async() => { await ParallelSort(arrayToSort, index + halfLen, length - halfLen, comparer); rightSortComplete.SetResult(true); }); T[] localCopyOfHalfOfArray = new T[halfLen]; accessor.Copy(arrayToSort, index, localCopyOfHalfOfArray, 0, halfLen); await MergeSortCore <T, T[], ArrayAccessor <T>, TComparer, TCompareAsEqualAction> .ParallelSort(localCopyOfHalfOfArray, 0, halfLen, comparer); await rightSortComplete.Task; Merge(localCopyOfHalfOfArray, arrayToSort, index, halfLen, length, comparer); } }
private void OnCompleted() { if (System.Threading.Interlocked.CompareExchange(ref mCompletedStatus, 1, 0) == 0) { Time = TimeWatch.GetElapsedMilliseconds() - mStartTime; mClient.Client.ClientError = null; mClient.Client.DataReceive = null; try { taskCompletionSource.SetResult(this); } finally { if (mClient.Client.IsConnected) { PipeStream pipeStream = mClient.Client.Stream.ToPipeStream(); if (pipeStream.Length > 0) { pipeStream.ReadFree((int)pipeStream.Length); } } } } }
private static Task HandleOverlayOnShow(MetroDialogSettings settings, MetroWindow window) { return(Task.Factory.StartNew(() => { window.Invoke(() => { var isCloseButtonEnabled = window.ShowDialogsOverTitleBar || settings == null || settings.OwnerCanCloseWithDialog; window.SetValue(MetroWindow.IsCloseButtonEnabledWithDialogPropertyKey, BooleanBoxes.Box(isCloseButtonEnabled)); }); }) .ContinueWith(task => { return window.Invoke(() => { if (!window.metroActiveDialogContainer.Children.OfType <BaseMetroDialog>().Any()) { return (settings == null || settings.AnimateShow ? window.ShowOverlayAsync() : Task.Factory.StartNew(() => window.Dispatcher.Invoke(new Action(window.ShowOverlay)))); } else { var tcs = new System.Threading.Tasks.TaskCompletionSource <object>(); tcs.SetResult(null); return tcs.Task; } }); }) .Unwrap()); }
public Task <bool> DisplayChildForm(Action <Form> setupChildForm, int height = 600, int width = 800, Func <Form, bool?> onClosing = null, Action <Form> onDisplay = null, bool useIsolatedModelForThisChildForm = false, bool isDialog = false) { var promise = new System.Threading.Tasks.TaskCompletionSource <bool>(); // default to use the parent's model, but some child will use a DataContext and need an isolated model var childFormModel = this.Model; if (useIsolatedModelForThisChildForm == true) { childFormModel = new BindableDynamicDictionary(); } var childForm = new Form(_parentForm: this, _model: childFormModel); setupChildForm(childForm); childForm.Display_Internal(height: height, width: width, onClosing: onClosing, onDisplay: onDisplay, isDialog: isDialog) .ContinueWith(t => { promise.SetResult(t.Result); }); return(promise.Task); }
private void ntpClient_TimeReceived(object sender, NtpTimeReceivedEventArgs e) { System.Diagnostics.Debug.WriteLine(e.CurrentTime); System.Diagnostics.Debug.WriteLine("NTP Local: " + e.CurrentTime.ToLocalTime().ToString()); System.Diagnostics.Debug.WriteLine("Local: " + DateTime.Now.ToString()); _GotTimeTaskCompletionSource.SetResult(e.CurrentTime); }
public void Second(Action printSecond) { var ignored = firstCompletionSource.Task.Result; // printSecond() outputs "second". Do not change or remove this line. printSecond(); secondCompletionSource.SetResult(new object()); }
public Task <bool> AddAsync(string key, object value) { Guard.Against.NullOrWhiteSpace(key, "key"); Guard.Against.Null(value, "value"); _cache.Set(key, value); TaskCompletionSource <bool> tcs = new System.Threading.Tasks.TaskCompletionSource <bool>(); tcs.SetResult(true); return(tcs.Task); }
/// <summary> /// Creates an async-compatible manual-reset event. /// </summary> /// <param name="set">Whether the manual-reset event is initially set or unset.</param> public AsyncManualResetEvent(bool set) { _sync = new object(); _tcs = new TaskCompletionSource <object>(); if (set) { //Enlightenment.Trace.AsyncManualResetEvent_Set(this, _tcs.Task); _tcs.SetResult(null); } }
static void Main(string[] args) { Options options = null; try { options = Args.Parse <Options>(args); } catch (ArgException e) { Console.WriteLine(string.Format("Problems with the command line options: {0}", e.Message)); Console.WriteLine(ArgUsage.GenerateUsageFromTemplate <Options>()); return; } var url = options.Server; // Blynk server address var authorization = options.Authorization; // Authorization token using (var client = new Client(url, authorization)) { client.Connect(); var tcs = new TaskCompletionSource <bool>(); client.OnAuthorized += v => tcs.SetResult(v); client.Login(); var authorized = tcs.Task.Result; if (authorized) { Console.WriteLine("Hardware client is authorized with given token"); client.OnVirtualWritePin += (id, value) => { Console.WriteLine($"Write Pin {id} has value {value}"); }; var counter = 0; client.OnVirtualReadPin += id => { Console.WriteLine($"Read Pin {id}"); client.WriteVirtualPin(id, counter++); }; var closeTcs = new System.Threading.Tasks.TaskCompletionSource <bool>(); Console.CancelKeyPress += (o, e) => { closeTcs.SetResult(true); }; Console.WriteLine("Test server is active. Press CTRL+C to stop."); closeTcs.Task.Wait(); Console.WriteLine("Stopping Test server."); } else { Console.WriteLine("Cannot authorize client with given token."); } client.Disconnect(); } }
private static Task HandleOverlayOnShow(MetroDialogSettings settings, MetroWindow window) { if (!window.metroActiveDialogContainer.Children.OfType <BaseMetroDialog>().Any()) { return(settings == null || settings.AnimateShow ? window.ShowOverlayAsync() : Task.Factory.StartNew(() => window.Dispatcher.Invoke(new Action(window.ShowOverlay)))); } else { var tcs = new System.Threading.Tasks.TaskCompletionSource <object>(); tcs.SetResult(null); return(tcs.Task); } }
private static Task HandleOverlayOnHide(MetroDialogSettings settings, MetroWindow window) { if (window.metroDialogContainer.Children.Count == 0) { return(settings == null || settings.AnimateHide ? window.HideOverlayAsync() : Task.Factory.StartNew(() => window.Dispatcher.Invoke(new Action(window.HideOverlay)))); } else { var tcs = new System.Threading.Tasks.TaskCompletionSource <object>(); tcs.SetResult(null); return(tcs.Task); } }
/// <summary> /// Begins to show the MetroWindow's overlay effect. /// </summary> /// <returns>A task representing the process.</returns> public System.Threading.Tasks.Task ShowOverlayAsync() { if (_OverlayBox == null) { throw new InvalidOperationException("OverlayBox can not be founded in this MetroWindow's template. Are you calling this before the window has loaded?"); } var tcs = new System.Threading.Tasks.TaskCompletionSource <object>(); if (IsOverlayVisible() && _OverlayStoryboard == null) { //No Task.FromResult in .NET 4. tcs.SetResult(null); return(tcs.Task); } Dispatcher.VerifyAccess(); _OverlayBox.Visibility = Visibility.Visible; var sb = (Storyboard)this.Template.Resources["OverlayFastSemiFadeIn"]; sb = sb.Clone(); EventHandler completionHandler = null; completionHandler = (sender, args) => { sb.Completed -= completionHandler; if (_OverlayStoryboard == sb) { _OverlayStoryboard = null; if (IsContentDialogVisible == false) { IsContentDialogVisible = true; } } tcs.TrySetResult(null); }; sb.Completed += completionHandler; _OverlayBox.BeginStoryboard(sb); _OverlayStoryboard = sb; return(tcs.Task); }
private Task HandleOverlayOnHide(IMetroWindow metroWindow , IMetroDialogFrameSettings settings) { if (!metroWindow.MetroActiveDialogContainer.Children.OfType <IBaseMetroDialogFrame>().Any()) { return(settings == null || settings.AnimateHide ? metroWindow.HideOverlayAsync() : Task.Factory.StartNew(() => metroWindow.Dispatcher.Invoke(new Action(metroWindow.HideOverlay)))); } else { var tcs = new System.Threading.Tasks.TaskCompletionSource <object>(); tcs.SetResult(null); return(tcs.Task); } }
internal static Task <FileStream> FromFile(Bridge.Internal.Html5.File file) { var completer = new System.Threading.Tasks.TaskCompletionSource <FileStream>(); var fileReader = new FileReader(); fileReader.OnLoad = () => { completer.SetResult(new FileStream(fileReader.Result, file.Name)); }; fileReader.OnError = (e) => { completer.SetException(new ErrorException(e.As <dynamic>().target.error.As <string>())); }; fileReader.ReadAsArrayBuffer(file); return(completer.Task); }
protected override Task PutAllTextAsync(string fileName, string contents) { var tcs = new System.Threading.Tasks.TaskCompletionSource <object>(); Task.Run(() => { var data = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); if (!System.IO.Directory.Exists(data)) { System.IO.Directory.CreateDirectory(data); } var fullFileName = Path.Combine(data, fileName); System.IO.File.WriteAllText(fullFileName, contents); tcs.SetResult(0); }); return(tcs.Task); }
async Task <long> Run() { TaskCompletionSource <long> tcs = new System.Threading.Tasks.TaskCompletionSource <long>(); var asncTask = Task.Run(() => Test()); asncTask.ContinueWith((a) => tcs.SetResult(a.Result)); var result = await Task.WhenAny(tcs.Task, Task.Delay(1000)); if (result.Id == tcs.Task.Id) { return(await tcs.Task); } else { throw new TimeoutException(); } }
public static Task MockSendAsync(Mock <HttpProjectConfigManager.HttpClient> HttpClientMock, string datafile = null, TimeSpan?delay = null, HttpStatusCode statusCode = HttpStatusCode.OK) { var t = new System.Threading.Tasks.TaskCompletionSource <bool>(); HttpClientMock.Setup(_ => _.SendAsync(It.IsAny <System.Net.Http.HttpRequestMessage>())) .Returns(() => { if (delay != null) { // This delay mocks the networking delay. And help to see the behavior when get a datafile with some delay. Task.Delay(delay.Value).Wait(); } return(System.Threading.Tasks.Task.FromResult <HttpResponseMessage>(new HttpResponseMessage { StatusCode = statusCode, Content = new StringContent(datafile ?? string.Empty) })); }) .Callback(() => { t.SetResult(true); }); return(t.Task); }
protected override Task PutStreamAsync(string fileName, Stream stream) { var tcs = new System.Threading.Tasks.TaskCompletionSource <object>(); Task.Run(() => { var data = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); if (!System.IO.Directory.Exists(data)) { System.IO.Directory.CreateDirectory(data); } var fullFileName = Path.Combine(data, fileName); using (var outputStream = System.IO.File.Open(fullFileName, FileMode.OpenOrCreate)) { stream.Seek(0, SeekOrigin.Begin); stream.CopyTo(outputStream); tcs.SetResult(0); } }); return(tcs.Task); }
async private void ViewTheDistancePage() { Random rnd = new Random(); timerCanceled = true; var tcs = new System.Threading.Tasks.TaskCompletionSource <bool>(); ///////////////////////////////////////// var content = new StackLayout(); foreach (var p in ClosePlaces) { var pful = new CustomControl.LayoutWithCircleImages(p.Id); content.Children.Add(pful); } var scrolbar = new ScrollView(); scrolbar.Content = content; var CloseButon = new StackLayout { Padding = new Thickness(35, 0) }; CloseButon.Children.Add( new Button { Text = "لا شكرا" , BackgroundColor = Color.White, TextColor = Color.Red, Command = new Command(async o => { var result = rnd.Next(2) == 1; await base.Navigation.PopAsync(); tcs.SetResult(result); } ) }); var total = new Grid { BackgroundColor = ZadSpecialDesigen.ZadWhite, RowDefinitions = { new RowDefinition { Height = new GridLength(80, GridUnitType.Star) }, new RowDefinition { Height = new GridLength(20, GridUnitType.Star) } } }; total.Children.Add(scrolbar, 0, 0); total.Children.Add(CloseButon, 0, 1); ContentPage c = new ContentPage { Title = "قائمة بالاماكن القريبة", BackgroundColor = ZadSpecialDesigen.ZadWhite, Content = total }; c.Disappearing += (o, e) => { timerCanceled = false; ClosePlaces.Clear(); }; await base.Navigation.PushAsync(c); }
/// <summary> /// Sets the result. /// </summary> /// <param name="result">The result.</param> public override void SetResult(object result) { _source.SetResult((TResult)result); }
public void First(Action printFirst) { // printFirst() outputs "first". Do not change or remove this line. printFirst(); firstCompletionSource.SetResult(new object()); }
static void Main(string[] args) { Options options = null; try { options = Args.Parse <Options>(args); } catch (ArgException e) { Console.WriteLine(string.Format("Problems with the command line options: {0}", e.Message)); Console.WriteLine(ArgUsage.GenerateUsageFromTemplate <Options>()); return; } var telldusUri = options.Telldus; if (string.IsNullOrEmpty(telldusUri)) { var found = new List <(string Ip, string Id)>(); string ip = null; using (var discover = new Discover(30303, options.Broadcast)) { discover.OnFoundDevice += (ipEnd, id) => { found.Add((ipEnd, id)); if (options.Debug) { Console.WriteLine($"ip {ipEnd}, id {id}"); } }; discover.Start(); for (int i = 0; i < 10; i++) { discover.Send(); } Task.Delay(2000).Wait(); discover.Stop(); } if (string.IsNullOrEmpty(options.Identification)) { ip = found.Select(v => v.Ip).FirstOrDefault(); } else { ip = found.Where(v => v.Item2.Contains(options.Identification)).Select(v => v.Item1).FirstOrDefault(); } if (ip != null) { telldusUri = $"ws://{ip}/ws"; } else { Console.WriteLine($"Cannot find telldus device with id {options.Identification}"); return; } } if (string.IsNullOrEmpty(telldusUri)) { Console.WriteLine("Cannot find a telldus device"); return; } // Connect to blynk server var url = options.Server; // Blynk server address var authorization = options.Authorization; // Authorization token using (var client = new Client(url, authorization)) { client.Connect(); var tcs = new TaskCompletionSource <bool>(); client.OnAuthorized += v => tcs.SetResult(v); client.Login(); var authorized = tcs.Task.Result; if (authorized) { Console.WriteLine("Hardware client is authorized with given token"); // Connect to Telldus device using (var ws = new TelldusClient(telldusUri)) { ws.ConnectAsync().Wait(); ws.OnMessage += m => { var id = (int)m["id"]; var type = (string)m["type"]; var time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); var name = (string)m["name"]; if (type == "device") { var state = (int)m["state"]; switch (state) { case 1: client.WriteVirtualPin(id, $"{time} {name} on\r\n"); break; case 2: client.WriteVirtualPin(id, $"{time} {name} off\r\n"); break; default: client.WriteVirtualPin(id, $"{time} {name} other state {state}\r\n"); break; } } else if (type == "sensor") { var valueType = (int)m["valueType"]; if (valueType == 1) { var value = (double)m["value"]; client.WriteVirtualPin(id, value); } } if (options.Debug) { Console.WriteLine(m.ToString()); } }; var closeTcs = new System.Threading.Tasks.TaskCompletionSource <bool>(); Console.CancelKeyPress += (o, e) => { closeTcs.SetResult(true); }; ws.StartMessageLoop(); Console.WriteLine("Server is active. Press CTRL+C to stop."); closeTcs.Task.Wait(); Console.WriteLine("Stopping server."); ws.CloseAsync().Wait(); } } else { Console.WriteLine("Cannot authorize client with given token."); } client.Disconnect(); } }