public static void PWM(int pinNumber) { var stopwatch = Stopwatch.StartNew(); var pin = GpioController.GetDefault().OpenPin(pinNumber); pin.SetDriveMode(GpioPinDriveMode.Output); workItemThread = Windows.System.Threading.ThreadPool.RunAsync( (source) => { // setup, ensure pins initialized ManualResetEvent mre = new ManualResetEvent(false); mre.WaitOne(1500); ulong pulseTicks = ((ulong)(Stopwatch.Frequency) / 1000) * 2; ulong delta; var startTime = stopwatch.ElapsedMilliseconds; while (stopwatch.ElapsedMilliseconds - startTime <= 300) { pin.Write(GpioPinValue.High); ulong starttick = (ulong)(stopwatch.ElapsedTicks); while (true) { delta = (ulong)(stopwatch.ElapsedTicks) - starttick; if (delta > pulseTicks) break; } pin.Write(GpioPinValue.Low); starttick = (ulong)(stopwatch.ElapsedTicks); while (true) { delta = (ulong)(stopwatch.ElapsedTicks) - starttick; if (delta > pulseTicks * 10) break; } } }, WorkItemPriority.High); }
private void MotorThread(IAsyncAction action) { while(true) { } }
private void gameThreadStart(IAsyncAction action) { this.GamePageModel.GameViewModel.GameModel.ShowPlayerScoreInDetails = this.Context.Settings.ShowPlayerScore; this.GamePageModel.PlayGame(); this.WriteGameResult(); this.Context.CurrentGame = null; }
/// <summary> /// 某个子异步动作完成后的,检查异步动作状态表,还有未完成的,继续等待。 /// 如果所有子动作都完成了,看有没有执行失败的动作,只有所有动作都执行成功,整个动作组才算执行成功。 /// </summary> /// <param name="action">完成工作的子异步动作</param> /// <param name="args">子异步动作完成工作时的参数</param> protected override void OnActionCompleted(IAsyncAction action, AsyncCompletedEventArgs args) { //注册异步动作状态 this.asyncActions[action] = args; //如果还有动作没有完成,直接返回 if ((from a in this.asyncActions.Values where a == null select a).Count() != 0) { return; } IsBusy = false; //如果有失败动作,把所有失败信息合并到一起,通知失败了 var errors = from a in this.asyncActions.Values where a.Error != null select a; if (errors.Count() != 0) { State = State.Error; //把所有错误结果填入结果中 foreach(IAsyncAction key in errors) { //把子的出错信息复制过来,子不能是异步动作组 Errors.Add(new ErrorInfo(key.Name, key.Error)); } OnCompleted(errors.First()); } //否则,通知成功 else { State = State.End; OnCompleted(new AsyncCompletedEventArgs(null, false, null)); } }
private async void PollInput(IAsyncAction operation) { while (_socket != null) { try { DataReaderLoadOperation drlo = reader.LoadAsync(2); await drlo.AsTask(_tokenSource.Token); short size = reader.ReadInt16(); byte[] data = new byte[size]; drlo = reader.LoadAsync((uint)size); await drlo.AsTask(_tokenSource.Token); reader.ReadBytes(data); if (ReportReceived != null) ReportReceived(this, new ReportReceivedEventArgs { Report = data }); } catch (TaskCanceledException) { return; } catch (System.Exception) { BrickDisconnected?.Invoke(this, new BrickDisconnectedEventArgs() { Details = "Brick disconnected due to unexpected behavior" }); } } }
public ServoDriver(GpioPin servoPin, ServoPulseModel servoPulseModel) { _servoPin = servoPin; _servoPin.SetDriveMode(GpioPinDriveMode.Output); _servoPulseModel = servoPulseModel; _servoBackgroundTask = Windows.System.Threading.ThreadPool.RunAsync(this.ServoBackgrounTask, Windows.System.Threading.WorkItemPriority.High); }
public void Start() { #if NETFX_CORE _asyncAction = ThreadPool.RunAsync(wi => ThreadProc()); #else _thread.Start(); #endif }
private void ThreadLogic(IAsyncAction action) { while (_running) { _callback(); _updateWaiter.WaitOne(SleepTime); } _joinWaiter.Set(); }
public virtual void Start() { if (IsAlive) return; lock (this) { if (IsAlive) return; threadPoolWorkItem = ThreadPool.RunAsync((_) => RunLoop()); } }
private void Leer_Click(object sender, RoutedEventArgs e) { var synth = new SpeechSynthesizer(); var voices = InstalledVoices.All.Where(v => v.Language == "es-ES").OrderByDescending(v => v.Gender); synth.SetVoice(voices.FirstOrDefault(v => v.Gender == VoiceGender.Male)); _task = synth.SpeakTextAsync("Esto es una prueba. Realmente dura mucho más de lo necesario. Si quieres puedes parar pulsando el botón Parar Voz"); }
/// <summary> /// Speaks the text. /// </summary> /// <param name="start">The start count.</param> /// <returns></returns> public void Speak(int? start = null) { if (start.HasValue) { Count = start.Value; //MessageBox.Show(Count.ToString()); } speakTask = synth.SpeakSsmlAsync(CreateSSML()); }
private async void Completed(IAsyncAction asyncInfo, AsyncStatus asyncStatus) { if (asyncStatus == AsyncStatus.Canceled) return; await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync( CoreDispatcherPriority.High, () => { HyperlinkButton.Visibility = _isCompleted ? Visibility.Visible : Visibility.Collapsed; greeting.Text = "bitti!"; }); }
private void OnConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { if (m_pConnectedSocket != null) { m_pConnectedSocket.Dispose(); m_pConnectedSocket = null; } m_pConnectedSocket = args.Socket; m_pCollectingTask = ThreadPool.RunAsync(CollectTelemetryData); var handler = OnClientConnected; handler?.Invoke(this, null); }
/// <summary> /// 子动作完成后,首先检查动作完成状态,如果有错误,终止执行,通知外界发生了什么错误。 /// 如果没有错误,则继续执行下面的动作。 /// </summary> /// <param name="action">完成工作的动作</param> /// <param name="args">子动作完成时的参数</param> protected override void OnActionCompleted(IAsyncAction action, AsyncCompletedEventArgs args) { //如果失败,且不能继续执行,直接通知失败,否则,继续下一个动作 if (args.Error != null && !ContinueOnError) { //通知前,还原index index = 0; IsBusy = false; State = State.Error; Error = args.Error.GetMessage(); OnCompleted(args); } else { Excute(); } }
private void MotorThread(IAsyncAction action) { //This motor thread runs on a high priority task and loops forever to pulse the motor as determined by the drive buttons while (true) { //If a button is pressed the pulsewidth is changed to cause the motor to spin in the appropriate direction //Write the pin high for the appropriate length of time if (currentPulseWidth != 0) { servoPin.Write(GpioPinValue.High); } //Use the wait helper method to wait for the length of the pulse Wait(currentPulseWidth); //The pulse if over and so set the pin to low and then wait until it's time for the next pulse servoPin.Write(GpioPinValue.Low); Wait(PulseFrequency - currentPulseWidth); } }
internal void Run(IAsyncAction action, CoreDispatcher uiDispatcher) { bool cont = true; AppTaskResult? lastResult = null; while (cont) { var task = TaskStack.Pop(); object data; bool success = task(Parameter, action, lastResult, out data); lastResult = new AppTaskResult(success, data, lastResult); cont = (SuccessFallbackLimit == -1 || SuccessFallbackLimit > CurrentLevel) && TaskStack.Count > 0; CurrentLevel++; } #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed if (action.Status != AsyncStatus.Canceled) uiDispatcher.RunAsync(CoreDispatcherPriority.High, () => { CompletedCallback(lastResult.Value); }); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed }
private void OnConnected(IAsyncAction action, AsyncStatus target) { if (target == AsyncStatus.Completed) { this.connection.Connected(); this.writer = new DataWriter(this.socket.OutputStream); this.reader = new DataReader(this.socket.InputStream); NetworkMessage m = new NetworkMessage(); m.MessageCategory = SystemMessages.SystemPrefix; m.MessageType = SystemMessages.Connect; AuthenticationInfo auth = new AuthenticationInfo(); auth.Username = this.id; m.MessageContent = NetworkSerializer.Serialize(auth); this.SendMessage(m); this.reader.InputStreamOptions = InputStreamOptions.Partial; DataReaderLoadOperation operation = this.reader.LoadAsync(256); operation.Completed = new AsyncOperationCompletedHandler<uint>(this.ReaderHasData); } }
private void button_Click(object sender, RoutedEventArgs e) { int count = 0; IAsyncAction a = Windows.System.Threading.ThreadPool.RunAsync((work) => { while (true) { Debug.WriteLine("Running thread: " + Environment.CurrentManagedThreadId); Debug.WriteLine("Work count: " + count++); if (work.Status == AsyncStatus.Canceled || count > 1000) { break; } } }); asyncAction = a; asyncAction.Completed = new AsyncActionCompletedHandler( async (IAsyncAction act, AsyncStatus status) => { Debug.WriteLine("Work complete, thread: " + Environment.CurrentManagedThreadId); //Debug.WriteLine("Work count when finished: " + count); await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High, new DispatchedHandler(() => { if (status == AsyncStatus.Canceled) { textBlock.Text = "Work threa canceled: " + count; } else { textBlock.Text = "Work thread complete: " + count; } })); }); }
private async void PollInput(IAsyncAction operation) { while(_socket != null) { try { DataReaderLoadOperation drlo = _reader.LoadAsync(2); await drlo.AsTask(_tokenSource.Token); short size = _reader.ReadInt16(); byte[] data = new byte[size]; drlo = _reader.LoadAsync((uint)size); await drlo.AsTask(_tokenSource.Token); _reader.ReadBytes(data); if(ReportReceived != null) ReportReceived(this, new ReportReceivedEventArgs { Report = data }); } catch (TaskCanceledException) { return; } } }
private async void PollInput(IAsyncAction operation) { while (!_tokenSource.IsCancellationRequested) { try { IBuffer sizeBuffer = new Buffer(2); await _socket.InputStream.ReadAsync(sizeBuffer, 2, InputStreamOptions.None); uint size = (uint)((sizeBuffer.GetByte(0) | sizeBuffer.GetByte(1) << 8)); if (size != 0) { IBuffer report = new Buffer(size); await _socket.InputStream.ReadAsync(report, size, InputStreamOptions.None); if (ReportReceived != null) ReportReceived(this, new ReportReceivedEventArgs { Report = report.ToArray() }); } } catch (Exception) { // swallow exceptions...if we tank here, it's likely a disconnect and we can't do much anyway } } }
public void Play(string p) { if (!string.IsNullOrEmpty(p)) { //string path = String.Format(adr + "{0}.wav", p); // path = String.Format(adr2 + "{0}.wav", p); // using (var stream = TitleContainer.OpenStream(path)) // { // if (stream != null) // { // var effect = SoundEffect.FromStream(stream); // FrameworkDispatcher.Update(); // effect.Play(); // } // } // } // else // { Deployment.Current.Dispatcher.BeginInvoke(() => { lock (lockObj) { try { if (cts != null) { cts.Cancel(); } cts = new CancellationTokenSource(); token = cts.Token; task = synth.SpeakTextAsync(p); token.Register(() => { if (Deployment.Current.Dispatcher.CheckAccess()) { if (task.Status == AsyncStatus.Started) { task.Cancel(); } } else { Deployment.Current.Dispatcher.BeginInvoke(() => { if (task.Status == AsyncStatus.Started) { task.Cancel(); } }); } }); } catch (Exception e) { } } }); } }
public static TaskAwaiter GetAwaiter(this IAsyncAction source) { return(AsTask(source).GetAwaiter()); }
internal void CompleteFromAsyncAction(IAsyncAction asyncInfo, AsyncStatus asyncStatus) { Complete(asyncInfo, null, asyncStatus); }
/// <summary> /// Tries to use the users location do get a city list from weather api /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void btnUseLocation_Tapped(object sender, TappedRoutedEventArgs e) { //Hide error message tblLocationDisabledMessage.Visibility = Visibility.Collapsed; //Hide search error message tblNoSearchResult.Visibility = Visibility.Collapsed; //Hide unknown error message tblUnknownError.Visibility = Visibility.Collapsed; //Hide connection error image imgConnectionError.Visibility = Visibility.Collapsed; //Set the loading image to visible imgLoading.Visibility = Visibility.Visible; //Run in a different thread so no blocking await System.Threading.Tasks.Task.Run(() => { //Get the location Location.GetLocation( (pos) => { //Load a city from accu Weather this.WAC.FindCityByCoordinates(pos, (result) => { //Convert the result to City City city = new City { Version = result.Version, Key = result.Key, Type = result.Type, Rank = result.Rank, LocalizedName = result.LocalizedName, AdministrativeArea = new AdministrativeArea { ID = result.AdministrativeArea.ID, LocalizedName = result.AdministrativeArea.LocalizedName }, Country = new Country { ID = result.Country.ID, LocalizedName = result.Country.LocalizedName } }; //Do the callback in UI thread IAsyncAction a = Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { //Add the city to the list this.cities = new List <City> { city }; //Show the list view lvCities.Visibility = Visibility.Visible; //Place the city to the search result list view lvCities.ItemsSource = this.cities; }); return(true); }, (err) => { //Do the callback in UI thread IAsyncAction a = Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { //Hide the list view lvCities.Visibility = Visibility.Collapsed; //Show error message tblNoSearchResult.Visibility = Visibility.Visible; //Hide the loading image imgLoading.Visibility = Visibility.Collapsed; //Show connection error image imgConnectionError.Visibility = Visibility.Visible; }); return(true); }); return(true); }, (err) => { System.Diagnostics.Debug.WriteLine(err); //Check if it is a permission error or it is an unknonwn error if (err == "Access to location is denied.") { //Show error message tblLocationDisabledMessage.Visibility = Visibility.Visible; //Hide the list view lvCities.Visibility = Visibility.Collapsed; } else { //Show unknown error message tblUnknownError.Visibility = Visibility.Visible; //Show the list view lvCities.Visibility = Visibility.Visible; } //Hide the loading image imgLoading.Visibility = Visibility.Collapsed; return(true); } ); }); }
public static void IgnoreException(this IAsyncAction action) { action.AsTask().IgnoreException(); }
private void OnActionFinished(IAsyncAction action) { // ReSharper disable once DelegateSubtraction action.EventActionFinished -= OnActionFinished; TryExecuteNextAction(); }
public static Task AsTask(this IAsyncAction source) => source.AsTask(CancellationToken.None);
internal static void WatchForError(this IAsyncAction self) => self.AsTask().WatchForError();
public void AddAction(IAsyncAction action) { _actions.Enqueue(action); }
public static void TrackAsyncAction(IAsyncAction action) { DisableView(null); action.Completed = (s, e) => Parent.Dispatcher.Begin(EnableView); }
private void startProcessingThread() { // Run thread to update UI if (gameMode == GameMode.Diagnostics) { runUIThread(); } // Run thread to read camera and make decisions mainThread = ThreadPool.RunAsync((s) => { if (gameMode != GameMode.Diagnostics) { showMessage("Warming up..."); warmUp(); hideMessage(); } long currentTimeMilliseconds = -1, previousTimeMilliseconds = -1; bool xMoved = false, yMoved = false; if (gameMode == GameMode.Game) { showScoreCanvas(); } else if (gameMode == GameMode.Diagnostics) { setOutputText("Ready"); } else if (gameMode == GameMode.Mirror) { showMessage("Mirror Mode"); } while (!stopThread) { currentTimeMilliseconds = Global.Stopwatch.ElapsedMilliseconds; // Check for new block every 20 ms, since the camera is 50hz if ((currentTimeMilliseconds - previousTimeMilliseconds) > 20 || previousTimeMilliseconds == -1) { // Start new thread to poll camera so that we reduce the chance of getting jitter ThreadPool.RunAsync((s1) => { try { var blocks = pixyCam.GetBlocks(10); if (blocks != null && blocks.Count > 0) { foreach (ObjectBlock block in blocks) { var position = getPuckPosition(block); // Check if we got a valid puck position if (position != CoordinateHelper.INVALID_POINT) { runDecisionThread(position); } } } else { if (robot.AI.GetPuckPosition() != null) { runDecisionThread(robot.AI.GetPuckPosition()); } } } catch (Exception err) { setOutputText("Error: " + err.Message); } }, WorkItemPriority.Low); previousTimeMilliseconds = currentTimeMilliseconds; } // Run the motors xMoved = robot.StepperX.Run(); yMoved = robot.StepperY.Run(); // If we're finished moving, go back to defense mode if (robot.StepperX.DistanceToGo() == 0 && robot.StepperY.DistanceToGo() == 0) { robot.AI.DoNotInterrupt = false; robot.AI.Mode = RobotMode.Defense; } } }, WorkItemPriority.High); }
public static ConfiguredTaskAwaitable TranslateWinRTTask(this IAsyncAction operation, string filePath, bool isDirectory = false) { return(TranslateWinRTTaskCore(operation, filePath, isDirectory).ConfigureAwait(false)); }
private async void ButtonSend_Click(object sender, RoutedEventArgs e) { string errorDescription = string.Empty; try { await _doOauthAsync(); TextStatus.Text = "Oauth is completed, ready to send email."; } catch (Exception ep) { errorDescription = string.Format("Failed to do oauth, exception: {0}", ep.Message); } if (!string.IsNullOrWhiteSpace(errorDescription)) { await new MessageDialog(errorDescription).ShowAsync(); TextStatus.Text = errorDescription; return; } if (string.IsNullOrWhiteSpace(TextTo.Text) && string.IsNullOrWhiteSpace(TextCc.Text)) { MessageDialog dlg = new MessageDialog("Please input a recipient at least!"); await dlg.ShowAsync(); TextTo.Text = ""; TextCc.Text = ""; TextTo.Focus(Windows.UI.Xaml.FocusState.Programmatic); return; } if (string.IsNullOrWhiteSpace(TextServer.Text)) { MessageDialog dlg = new MessageDialog("Please input server address!"); await dlg.ShowAsync(); TextServer.Text = ""; TextServer.Focus(Windows.UI.Xaml.FocusState.Programmatic); return; } ButtonSend.IsEnabled = false; ProgressBarSending.Value = 0; ProgressBarSending.Visibility = Visibility.Visible; PageViewer.ChangeView(0, PageViewer.ScrollableHeight, 1); this.Focus(FocusState.Programmatic); try { await _sendEmailAsync(); } catch (Exception ep) { errorDescription = string.Format("Failed to do oauth, exception: {0}", ep.Message); } if (!string.IsNullOrWhiteSpace(errorDescription)) { await new MessageDialog(errorDescription).ShowAsync(); TextStatus.Text = errorDescription; } ProgressBarSending.Visibility = Visibility.Collapsed; _asyncCancel = null; ButtonSend.IsEnabled = true; ButtonCancel.IsEnabled = false; ButtonClear.IsEnabled = true; }
private void Button_Click3(object sender, RoutedEventArgs e) { byte[] recvBuf = new byte[1024]; byte[] frameinfo = new byte[100]; int last_time_tick; last_time_tick = System.Environment.TickCount; tutk.iotc.AVRecvFrmNo frameNO = new tutk.iotc.AVRecvFrmNo(); IAsyncAction Thread1 = Windows.System.Threading.ThreadPool.RunAsync((THREAD1) => { int fps_cnt = 0; CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync( Windows.UI.Core.CoreDispatcherPriority.High, new Windows.UI.Core.DispatchedHandler(() => { UpdateUI("Received Thread Start"); })); if (startIpcamStream()) { IAsyncAction videoThread = Windows.System.Threading.ThreadPool.RunAsync((VIDEOTHREAD) => { const int VIDEO_BUF_SIZE = 100000; const int FRAME_INFO_SIZE = 16; int ret; byte[] frameInfo = new byte[FRAME_INFO_SIZE]; byte[] videoBuffer = new byte[VIDEO_BUF_SIZE]; tutk.iotc.AVRecvFrmNo frameNumber = new tutk.iotc.AVRecvFrmNo(); CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync( Windows.UI.Core.CoreDispatcherPriority.High, new Windows.UI.Core.DispatchedHandler(() => { UpdateUI("VideoThread Start"); })); while (running) { ret = AV1.avRecvFrameData(avIndex, videoBuffer, VIDEO_BUF_SIZE, frameInfo, FRAME_INFO_SIZE, frameNumber); if (ret == -20015 || ret == -20016 || ret == -20010) { break; } else if (ret < 0) { new System.Threading.ManualResetEvent(false).WaitOne(50); continue; } } }); IAsyncAction audioThread = Windows.System.Threading.ThreadPool.RunAsync((AUDIOTHREAD) => { const int AUDIO_BUF_SIZE = 1024; const int FRAME_INFO_SIZE = 16; byte[] frameInfo = new byte[FRAME_INFO_SIZE]; byte[] audioBuffer = new byte[AUDIO_BUF_SIZE]; int ret; tutk.iotc.AVRecvFrmNo frameNumber = new tutk.iotc.AVRecvFrmNo(); CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync( Windows.UI.Core.CoreDispatcherPriority.High, new Windows.UI.Core.DispatchedHandler(() => { UpdateUI("AudioThread Start"); })); while (running) { ret = AV1.avCheckAudioBuf(avIndex); if (ret < 0) { break; } else if (ret < 3) { new System.Threading.ManualResetEvent(false).WaitOne(120); continue; } ret = AV1.avRecvAudioData(avIndex, audioBuffer, AUDIO_BUF_SIZE, frameInfo, FRAME_INFO_SIZE, frameNumber); if (ret == -20015 || ret == -20016 || ret == -20010) { break; } else if (ret < 0) { new System.Threading.ManualResetEvent(false).WaitOne(50); continue; } } }); } }); }
/// <summary> /// Enables Task's ConfigureAwait for IAsyncActions /// </summary> /// <param name="action">Source IAsyncAction</param> /// <param name="continueOnCapturedContext">true to attempt to marshal the continuation back to the original context /// captured; otherwise, false.</param> /// <returns>An object used to await this IAsyncAction</returns> public static ConfiguredTaskAwaitable ConfigureAwait(this IAsyncAction action, bool continueOnCapturedContext) { return(action.AsTask().ConfigureAwait(continueOnCapturedContext)); }
public static void WatchForError(this IAsyncAction self) { self.AsTask().WatchForError(); }
private static void WaitForIdleWorker(IAsyncAction action) { _error = IdleSynchronizer.TryWait(out _log); }
public static Task AsTask(this IAsyncAction source, CancellationToken cancellationToken) => source.AsTaskCore(cancellationToken);
private async void tbxCitySearch_KeyDown(object sender, KeyRoutedEventArgs e) { //Hide error message tblLocationDisabledMessage.Visibility = Visibility.Collapsed; //Hide search error message tblNoSearchResult.Visibility = Visibility.Collapsed; //Hide unknown error message tblUnknownError.Visibility = Visibility.Collapsed; //Hide connection error image imgConnectionError.Visibility = Visibility.Collapsed; //Cast the sender TextBox tb = (TextBox)sender; //Dont search unles there is atleast three characters if (tb.Text.Length > 2) { //Set the loading image to visible imgLoading.Visibility = Visibility.Visible; //Run in a different thread so no blocking await System.Threading.Tasks.Task.Run(async() => { //Cast the sender String searchstring = ""; //Has to get hold of the textbox from the UI await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { searchstring = tb.Text; }); //Load the cities WAC.GetCityListByAutoComplete(searchstring, (Cities) => { //Do the callback in UI thread IAsyncAction a = Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { //Set the new city list this.cities = Cities; //Update the view lvCities.ItemsSource = Cities; //Hide the loading image imgLoading.Visibility = Visibility.Collapsed; }); return(true); }, (error) => { //Do the callback in UI thread IAsyncAction a = Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { System.Diagnostics.Debug.WriteLine(error); //Hide the list view lvCities.Visibility = Visibility.Collapsed; //Show unknown error message tblUnknownError.Visibility = Visibility.Visible; //Hide the loading image imgLoading.Visibility = Visibility.Collapsed; //Show connection error image imgConnectionError.Visibility = Visibility.Visible; }); return(true); }); }); } }
public async void ConnectToServiceAsync(object sender, RoutedEventArgs e) { StorageFolder local_folder = App.appData.LocalFolder; StorageFolder devices_folder = await local_folder.CreateFolderAsync("devices_folder", CreationCollisionOption.OpenIfExists); StorageFile bluetooth_file = (StorageFile)await devices_folder.TryGetItemAsync("bluetooth_file.txt"); MenuFlyoutItem command = sender as MenuFlyoutItem; string bluetooth_file_line=null; //if file doesn't exist, return and wanting to connect at initialization, return if(bluetooth_file == null && command == null) { return; } //read from bluetooth file if (bluetooth_file != null) { bluetooth_file_line = await FileIO.ReadTextAsync(bluetooth_file); System.Diagnostics.Debug.WriteLine(bluetooth_file_line); } string serviceIDString; string serviceNameString; if (command == null) { string[] parse_bluetooth_file_line = bluetooth_file_line.Split(','); serviceNameString = parse_bluetooth_file_line[0]; serviceIDString = parse_bluetooth_file_line[1]; } else { DeviceInformation serviceInfo = (DeviceInformation)selected_device_global; serviceIDString = command.Name; serviceNameString = command.Text; } //this.State = BluetoothConnectionState.Connecting; this.Disconnect(); try { // Initialize the target Bluetooth RFCOMM device service connectService = RfcommDeviceService.FromIdAsync(serviceIDString); rfcommService = await connectService; if (rfcommService != null) { // Create a socket and connect to the target socket = new StreamSocket(); connectAction = socket.ConnectAsync(rfcommService.ConnectionHostName, rfcommService.ConnectionServiceName, SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication); await connectAction;//to make it cancellable writer = new DataWriter(socket.OutputStream); reader = new DataReader(socket.InputStream); Task listen = ListenForMessagesAsync(); this.State = BluetoothConnectionState.Connected; //write device information if (command != null) { StorageFile device_info = await devices_folder.CreateFileAsync("bluetooth_file.txt", CreationCollisionOption.ReplaceExisting); await FileIO.WriteTextAsync(device_info, serviceNameString+ ','+ serviceIDString); } connectedBluetoothDeviceName = serviceNameString; if(changedName != null) changedName.Invoke(this, EventArgs.Empty); } else { OnExceptionOccuredEvent(this, new Exception("Unable to create service.\nMake sure that the 'bluetooth.rfcomm' capability is declared with a function of type 'name:serialPort' in Package.appxmanifest.")); } } catch (TaskCanceledException) { this.State = BluetoothConnectionState.Disconnected; } catch (Exception ex) { this.State = BluetoothConnectionState.Disconnected; OnExceptionOccuredEvent(this, ex); } }
public static void CreateTimer(int d) { //定时器 TimeSpan delay = TimeSpan.FromSeconds(5); DelayTimer = ThreadPoolTimer.CreateTimer( (source) => { Debug.WriteLine("启动定时器任务"); //从控机进入待机状态 SlaveModel.GetInstance().IsWorking = false; if (asyncSelfChange == null) { asyncSelfChange = ThreadPool.RunAsync( async(selfChange) => { while (true) { //如果工作项还没有开始就调用了 workItem.Cancel 方法,工作项 //就会被终止。工作项如果开始工作了,那么它就会一直运行到结束,除非它 //支持“取消”操作。 //如果让工作项支持“取消”操作,这个工作项应该检查 IAsyncAction.Status //是否为取消操作,并且当取消的时候执行退出操作 Debug.WriteLine("selfChange Status:" + selfChange.Status); Debug.WriteLine("asyncSelfChange Status:" + asyncSelfChange.Status); if (SlaveModel.GetInstance().IsWorking == false) { if (SlaveModel.GetInstance().WorkMode == "Cooling") { if (SlaveModel.GetInstance().CTemp + 0.5 > SlaveModel.GetInstance().InitDTemp) { SlaveModel.GetInstance().CTemp = SlaveModel.GetInstance().InitDTemp; } else { SlaveModel.GetInstance().CTemp += 0.5; } } else { if (SlaveModel.GetInstance().CTemp - 0.5 < 18) { SlaveModel.GetInstance().CTemp = 18.0; } else { SlaveModel.GetInstance().CTemp -= 0.5; } } } await Task.Delay(d); } }); } }, delay, (source) => { Debug.WriteLine("定时器完成"); }); }
/// <summary> /// Initiates synthesis of a speech synthesis markup language (SSML) document, which allows for finer and more /// robust control than plain text. /// </summary> /// <param name="ssmlToSpeak"> The body fo the SSML document to be spoken </param> private void StartSpeakingSsml(string ssmlToSpeak) { // Begin speaking using our synthesizer, wiring the completion event to stop tracking the action when it // finishes. this.CurrentSynthesizerAction = this.Synthesizer.SpeakSsmlAsync(ssmlToSpeak); this.CurrentSynthesizerAction.Completed = new AsyncActionCompletedHandler( (operation, asyncStatus) => { Dispatcher.BeginInvoke(() => { this.CurrentSynthesizerAction = null; }); }); }
private async void webview1_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args) { //检查是否为词条 if (daima.huancun.panduan_leixing(args.Uri.AbsoluteUri) == 2) { //检查是否为新链接 if ((daima.huancun.chitiao.daohan_duifa[daima.huancun.chitiao.daohan_duifa.Count - 1].StartsWith(args.Uri.AbsoluteUri) || args.Uri.AbsoluteUri.StartsWith(daima.huancun.chitiao.daohan_duifa[daima.huancun.chitiao.daohan_duifa.Count - 1])) == false) { //启动进度条 jindutiao(true); //取消导航 args.Cancel = true; //检查是否为内链 不用修改元素 string pattern = @"(#cite_note-)"; Regex rx = new Regex(pattern); if (rx.IsMatch(args.Uri.AbsoluteUri) == false) { //检查是否与上一个导航一致 if (daima.huancun.chitiao.daohan_duifa[daima.huancun.chitiao.daohan_duifa.Count - 1] != args.Uri.AbsoluteUri) { daima.huancun.chitiao.daohan_duifa.Add(args.Uri.AbsoluteUri); } } //触发事件 daima.huancun.chitiao.Kaishitishi("跳转", 2); //完成 jindutiao(false); } else { //检查是否为同一个链接 if (danqian_lianjie.StartsWith(args.Uri.AbsoluteUri) || args.Uri.AbsoluteUri.StartsWith(danqian_lianjie)) { } else { danqian_lianjie = args.Uri.AbsoluteUri; //启动进度条 jindutiao(true); //因为已经开始导航 只要修改元素 IAsyncAction asyncAction = Windows.System.Threading.ThreadPool.RunAsync( (workItem) => { xiugai_wangye(); }); } } } else//用浏览器打开 { //启动进度条 jindutiao(true); //取消导航 args.Cancel = true; await Launcher.LaunchUriAsync(new Uri(args.Uri.AbsoluteUri)); //向后导航 webview1.Navigate(new Uri(danqian_lianjie)); //完成 jindutiao(false); } }
public static void CreatePeriodicRequest(int d) { //workItem.Status == AsyncStatus.Canceled asyncRequest = ThreadPool.RunAsync( async(workItem) => { while (true) { //延迟时间 await Task.Delay(d); Debug.WriteLine("进入正常工作线程"); double ctemp = SlaveModel.GetInstance().CTemp; double dtemp = SlaveModel.GetInstance().DTemp; string workMode = SlaveModel.GetInstance().WorkMode; string speed = SlaveModel.GetInstance().Speed; if (workMode == "Cooling") { ctemp -= 1.0; if (ctemp < dtemp) { ctemp = dtemp; } } else { ctemp += 1.0; if (ctemp > dtemp) { ctemp = dtemp; } } string message = JsonOperation.GetInstance().PraseJson(2, "req", dtemp, ctemp, speed, workMode); await TcpClient.GetInstance().SendToTcpServer(message); //启动5秒定时器 CreateTimer(5000); //等待Ack string JsonString = await TcpClient.GetInstance().WaitTcpServer(); Debug.WriteLine(JsonOperation.GetInstance().DeserializeJson("ack", JsonString)); //如果收到的消息是ack if (JsonOperation.GetInstance().DeserializeJson("ack", JsonString)) { //取消定时器 DelayTimer.Cancel(); //停止自己变化线程 if (asyncSelfChange != null) { asyncSelfChange.Cancel(); Debug.WriteLine("停止自己变化"); } //累加消费金额 SlaveModel.GetInstance().Cost += double.Parse(JsonOperation.GetInstance().DeserializeJson(JsonString)); //如果当前正在工作,就更新温度,否则就设置为开始工作 if (SlaveModel.GetInstance().IsWorking == true) { SlaveModel.GetInstance().CTemp = ctemp; SlaveModel.GetInstance().DTemp = dtemp; } else { SlaveModel.GetInstance().IsWorking = true; } } } }); }
/// <summary> /// Processes a given query string for searching. If the string is syntactically meaningful (not empty or /// '...', the latter of which indicates a resolution error likely stemming from network unavailability), /// a search will be executed, either with or without spoken feedback depending on preference. Without a /// syntactically meaningful query, the user will be prompted for a query if silence isn't requested. /// </summary> /// <param name="searchQuery"> the search query to attempt action on </param> /// <param name="actSilently"> whether or not to only take actions without audio feedback </param> private void HandleSearchQuery(string searchQuery, bool actSilently) { if (!String.IsNullOrEmpty(searchQuery) && (searchQuery != "...")) { FadeInfoButtons(false); StartSearchQueryNavigation(searchQuery, !actSilently); } else if (!actSilently) { this.CurrentSynthesizerAction = this.Synthesizer.SpeakSsmlAsync( AppResources.SpokenEmptyInvocationQuery); this.CurrentSynthesizerAction.Completed = new AsyncActionCompletedHandler( (operation, asyncStatus) => { Dispatcher.BeginInvoke(() => { this.CurrentSynthesizerAction = null; StartListening(); }); }); } else { // If there's no query text available and we can't speak to prompt the user, there's nothing to do. } }
public static Task AsTask(this IAsyncAction source) { return(AsTask(source, CancellationToken.None)); }
//-------------------------------------------------------------- // This method runs in a parallel task. private void GameLoopTaskAction(IAsyncAction action) { // Run until MyGame is disposed. while (!_isDisposed) { // Pulse the clock, which updates the timer. The timer will call GameLoop at the // desired frequency. lock (Lock) _clock.Update(); // Halt the thread until the next vertical blank is reached. // This ensures the app isn't updating and rendering faster than the display can refresh, // which would unnecessarily spend extra CPU and GPU resources. This helps improve battery // life. _dxgiOutput.WaitForVerticalBlank(); } }
private void BackgroundTaskInitializationCompleted(IAsyncAction action, AsyncStatus status) { if (status == AsyncStatus.Completed) { Debug.WriteLine("Background Audio Task initialized"); } else if (status == AsyncStatus.Error) { Debug.WriteLine("Background Audio Task could not initialized due to an error ::" + action.ErrorCode.ToString()); } }
private void CalculateAsync(IAsyncAction asyncAction) { this.Model.Calculate(); }
public void ResultChip(DocReader.PassService.ChipData cd) { if (cd.MessageLOG != null) { IAsyncAction act = Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { if (cd.CAStatus != null) { CAStatus.IsChecked = cd.CAStatus; } if (!string.IsNullOrEmpty(cd.FirstName)) { firstName.Text = cd.FirstName.Trim('<'); } if (!string.IsNullOrEmpty(cd.LastName)) { lastName.Text = cd.LastName.Trim('<'); } if (!string.IsNullOrEmpty(cd.Citizenship)) { citizenship.Text = cd.Citizenship; } if (cd.DG14Integrity != null) { dg14CRC.IsChecked = cd.DG14Integrity; } if (cd.DG1Integrity != null) { dg1CRC.IsChecked = cd.DG1Integrity; } dg2CRC.IsChecked = cd.DG2Integrity; if (!string.IsNullOrEmpty(cd.IssuingCountry)) { issuingCountry.Text = cd.IssuingCountry; } SODIntegrity.IsChecked = cd.SODIntegrity; CSCATrusted.IsChecked = cd.IsDSTrusted; if (!string.IsNullOrEmpty(cd.ExpirationDate)) { validityPeriod.Text = cd.ExpirationDate; } if (!string.IsNullOrEmpty(cd.DOB)) { dob.Text = cd.DOB; } if (!string.IsNullOrEmpty(cd.Citizenship)) { citizenship.Text = cd.Citizenship; } if (!string.IsNullOrEmpty(cd.IssuingCountry)) { issuingCountry.Text = cd.IssuingCountry; } if (!string.IsNullOrEmpty(cd.DocumentNumber)) { docNumber.Text = cd.DocumentNumber; } IsPACE.IsChecked = cd.IsPACEReadingProc; JPEG2000.IsChecked = cd.IsJPEG2000; foreach (string m in cd.MessageLOG) { AddMessageToList(m); } }); Task t = act.AsTask(); } }
/// <summary> /// "Forgets" the given task, but still tries to dispatch exception somewhere the user / developer /// can see them. /// </summary> /// <param name="asyncAction">The action to be fired.</param> public static async void FireAndForget(this IAsyncAction asyncAction) { await asyncAction; }
private async Task _sendEmailAsync() { var smtp = new SmtpClient(); // add event handler smtp.Authorized += OnAuthorized; smtp.Connected += OnConnected; smtp.Securing += OnSecuring; smtp.SendingDataStream += OnSendingDataStream; var server = new SmtpServer(TextServer.Text); int[] ports = new int[] { 25, 587, 465 }; server.Port = ports[ListPorts.SelectedIndex]; server.ConnectType = SmtpConnectType.ConnectSSLAuto; server.Protocol = ServerProtocol.SMTP; server.User = _oauthWrapper.OauthProvider.UserEmail; server.Password = _oauthWrapper.OauthProvider.AccessToken; server.AuthType = SmtpAuthType.XOAUTH2; // For evaluation usage, please use "TryIt" as the license code, otherwise the // "Invalid License Code" exception will be thrown. However, the trial object only can be used // with developer license // For licensed usage, please use your license code instead of "TryIt", then the object // can used with published windows store application. var mail = new SmtpMail("TryIt"); mail.From = new MailAddress(_oauthWrapper.OauthProvider.UserEmail); var replyTo = new MailAddress(TextFrom.Text); if (string.Compare(replyTo.Address, _oauthWrapper.OauthProvider.UserEmail, StringComparison.OrdinalIgnoreCase) != 0) { mail.ReplyTo = new MailAddress(TextFrom.Text); } // If your Exchange Server is 2007 and used Exchange Web Service protocol, please add the following line; // oMail.Headers.RemoveKey("From"); mail.To = new AddressCollection(TextTo.Text); mail.Cc = new AddressCollection(TextCc.Text); mail.Subject = TextSubject.Text; if (!CheckHtml.IsOn) { mail.TextBody = TextEditor.Text; } else { string html = await HtmlEditor.InvokeScriptAsync("getHtml", null); html = "<html><head><meta charset=\"utf-8\" /></head><body style=\"font-family:Calibri;font-size: 15px;\">" + html + "<body></html>"; await mail.ImportHtmlAsync(html, Windows.ApplicationModel.Package.Current.InstalledLocation.Path, ImportHtmlBodyOptions.ErrorThrowException | ImportHtmlBodyOptions.ImportLocalPictures | ImportHtmlBodyOptions.ImportHttpPictures | ImportHtmlBodyOptions.ImportCss); } int count = _attachments.Count; for (int i = 0; i < count; i++) { await mail.AddAttachmentAsync(_attachments[i]); } ButtonCancel.IsEnabled = true; TextStatus.Text = String.Format("Connecting {0} ...", server.Server); // You can genereate a log file by the following code. // oSmtp.LogFileName = "ms-appdata:///local/smtp.txt"; _asyncCancel = smtp.SendMailAsync(server, mail); await _asyncCancel; TextStatus.Text = "Completed"; }
public override void PlayGame() { this.GamePageModel.SetupGame(); this.gameThread = Windows.System.Threading.ThreadPool.RunAsync(new WorkItemHandler(gameThreadStart)); }
public static ConfiguredTaskAwaitable DontSync(this IAsyncAction self) { return(self.AsTask().ConfigureAwait(false)); }
public void Recieve(IAsyncAction operation) { while (realm.listenSocket) { Task.Delay(1); //if (clientSocket.Available > 0) { DataReader reader = new DataReader(clientSocket.InputStream); var size = reader.UnconsumedBufferLength; DataBuffer = new byte[size]; var buff = reader.ReadBuffer(size); CryptographicBuffer.CopyToByteArray(buff, out DataBuffer); HandleRealmData(DataBuffer); } } clientSocket.Dispose(); }
/// <summary> /// Focuses the compose text box. /// </summary> private void FocusComposeTextBox() { IAsyncAction focusAction = this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => this.ComposeTextBox.FocusText()); }
//Metodo que nos dara la conexion al dispositivo seleccionado private async void ConnectToServiceAsync(IUICommand command) { //Se obtiene el Id del dispositivo seleccionado DeviceInformation serviceInfo = (DeviceInformation)command.Id; //el estado de la conexion se pondra conectando this.State = BluetoothConnectionState.Connecting; try { //Inicializa el servicio del dispositivo RFCOMM de Bluetooth de destino connectService = RfcommDeviceService.FromIdAsync(serviceInfo.Id); rfcommService = await connectService; if (rfcommService != null) { //Se inicializa el socket socket = new StreamSocket(); connectAction = socket.ConnectAsync(rfcommService.ConnectionHostName, rfcommService.ConnectionServiceName, SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication); //Puedes Cancelar la conexion await connectAction; //Se inicializan las variables que envian y reciben los mensajes writer = new DataWriter(socket.OutputStream); reader = new DataReader(socket.InputStream); Task listen = ListenForMessagesAsync(); //se cambia el estado de conexion del bluetooth a conectado this.State = BluetoothConnectionState.Connected; } else OnExceptionOccuredEvent(this, new Exception("No se pudo connectar al servicio.\n Verifca que 'bluetooth.rfcomm' capabilityes es declarado con la funcion de tipo 'name:serialPort' en Package.appxmanifest.")); } catch (TaskCanceledException) { this.State = BluetoothConnectionState.Disconnected; } catch (Exception ex) { this.State = BluetoothConnectionState.Disconnected; OnExceptionOccuredEvent(this, ex); } }
/// <summary> /// Removes the action /// </summary> /// <param name="action"></param> public void Remove(IAsyncAction action) { throw new NotImplementedException(); }
/// <summary> /// Запуск процесса загрузки данных /// </summary> public void StartGetDataProcess() { IAsyncAction asyncAction = ThreadPool.RunAsync((a) => _pictureQueryItemJsonService.ProcessPictureQuery()); asyncAction.Completed = new AsyncActionCompletedHandler((IAsyncAction asyncInfo, AsyncStatus asyncStatus) => CompleteGetDataProcess()); }
/// <summary> /// Does nothing. /// </summary> /// <param name="task">The task.</param> public static void Forget(this IAsyncAction task) { }