/// <summary> /// this method just creates new StreamSocketListener and registers listener for new conenctions recived and then binds this listener to port specified by user. /// If you call the method without arguments, it defaults to port 8000. /// Must be called before server starts to listen to requests. /// </summary> public void Start(string serviceName = "8000") { Windows.Foundation.IAsyncAction result = null; if (string.IsNullOrEmpty(serviceName)) { throw new InvalidDataException("Invalid service name in Start(string)"); } try { listener = new StreamSocketListener(); listener.ConnectionReceived += (sender, args) => ProcessRequestAsync(args.Socket); #pragma warning disable CS4014 result = listener.BindServiceNameAsync(serviceName); #pragma warning restore CS4014 } catch (UnauthorizedAccessException e) { Debug.WriteIf(_debug, "Missing capability, please modify Package.appxmanifest in your main project to include Internet (client) and Internet (Client&Server)."); throw new UnauthorizedAccessException("Missing capability, please modify Package.appxmanifest in your main project to include Internet (client) and Internet (Client&Server) capabilities.", e); } catch (Exception e) { Debug.WriteLine("Error occured in connection from remote host (" + e.Message + ")."); return; } if (result.ErrorCode != null) { Debug.WriteLine("Error when binding to port " + serviceName + " Error code: " + result.ErrorCode.HResult); throw new Exception("Error while binding to the port.", result.ErrorCode); } }
public async Task RemoveContact(Contact contactToRemove) { await Task.Run(() => { switch (MsnpVersion) { case "MSNP12": TransactionId++; nsSocket.SendCommand($"REM {TransactionId} FL {contactToRemove.GUID}\r\n"); break; case "MSNP15": TransactionId++; soapRequests.AbContactDelete(contactToRemove); string contactPayload = ReturnXMLContactPayload(contactToRemove); int payloadLength = Encoding.UTF8.GetBytes(contactPayload).Length; nsSocket.SendCommand($"RML {TransactionId} {payloadLength}\r\n{contactPayload}"); break; default: throw new Exceptions.VersionNotSelectedException(); } Windows.Foundation.IAsyncAction task = Windows.ApplicationModel.Core.CoreApplication.MainView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { ContactsInForwardList.Remove(contactToRemove); ContactsInPendingOrReverseList.Remove(contactToRemove); }); DatabaseAccess.DeleteContactFromTable(UserInfo.Email, contactToRemove); }); }
public void HandleUbx() { string personalMessage; string[] ubxParameters = currentResponse.Split(" "); string principalEmail = ubxParameters[1]; string lengthString = ""; switch (MsnpVersion) { case "MSNP12": lengthString = ubxParameters[2]; break; case "MSNP15": lengthString = ubxParameters[3]; break; default: throw new Exceptions.VersionNotSelectedException(); } int ubxLength; int.TryParse(lengthString, out ubxLength); string payload = SeparatePayloadFromResponse(nextResponse, ubxLength); XmlDocument personalMessagePayload = new XmlDocument(); try { personalMessagePayload.LoadXml(payload); string xPath = "//Data/PSM"; XmlNode PSM = personalMessagePayload.SelectSingleNode(xPath); personalMessage = PSM.InnerText; } catch (XmlException) { personalMessage = "XML error"; } Windows.Foundation.IAsyncAction task = Windows.ApplicationModel.Core.CoreApplication.MainView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { var contactsWithPersonalMessage = from contact in ContactList where contact.Email == principalEmail select contact; foreach (Contact contact in contactsWithPersonalMessage) { contact.PersonalMessage = personalMessage; DatabaseAccess.UpdateContact(UserInfo.Email, contact); } var contactWithPersonalMessageInForwardList = from contact in ContactsInForwardList where contact.Email == principalEmail select contact; foreach (Contact contact in contactWithPersonalMessageInForwardList) { contact.PersonalMessage = personalMessage; } }); SeparateAndProcessCommandFromResponse(nextResponse, ubxLength); }
public static void StartEngine() { // Initialize the plug, through what we will communicate with the engine _thePlug = new WindowsRTPlug(); Plug.Init(_thePlug); // Run the engine in async mode Windows.Foundation.IAsyncAction action = Windows.System.Threading.ThreadPool.RunAsync(delegate { new Engine().Run(new string[] { }); }, WorkItemPriority.Normal); }
void StopRenderLoop() { if (_renderLoopWorker != null) { _swapChainEvent.Set(); _renderLoopWorker.Cancel(); _renderLoopWorker = null; } }
private void UpdateDownloadStatusOnUiThread(double percentageFinished, string message) { // The ignore variable is to silence an async warning. Seems bad but // they did it in the BackgroundTransfer example 🤔 Windows.Foundation.IAsyncAction ignore = CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync( CoreDispatcherPriority.Normal, () => { DownloadStatus = message; DownloadPercentFinished = percentageFinished; }); }
// Posts a single atomic action for asynchronous execution on the game loop thread. public override void Post(SendOrPostCallback callback, object state) { Windows.Foundation.IAsyncAction action = this.control.RunOnGameLoopThreadAsync(() => { // Re-register ourselves as the current synchronization context, // to work around CLR issues where this state can sometimes get nulled out. SynchronizationContext.SetSynchronizationContext(this); callback(state); }); }
//Loads the user's songs from their files. Should only be done to initially discover their music in the future. /* public static void GetSongList() * { * Windows.System.Threading.ThreadPool.RunAsync(DisplayFiles, Windows.System.Threading.WorkItemPriority.High); * }*/ //Saves the position in the song every second, public static async void PeriodicallySave(Windows.Foundation.IAsyncAction action) { while (true) { await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { SavePlace(); }); Thread.Sleep(1000); //Updates every second. } }
/// <summary> /// For the given bitmap renders filtered thumbnails for each filter in given list and populates /// the given wrap panel with the them. /// /// For quick rendering, renders 10 thumbnails synchronously and then releases the calling thread. /// </summary> /// <param name="bitmap">Source bitmap to be filtered</param> /// <param name="side">Side length of square thumbnails to be generated</param> /// <param name="list">List of filters to be used, one per each thumbnail to be generated</param> /// <param name="panel">Wrap panel to be populated with the generated thumbnails</param> private async Task RenderThumbnailsAsync(Bitmap bitmap, int side, List <FilterModel> list, WrapPanel panel) { using (EditingSession session = new EditingSession(bitmap)) { int i = 0; foreach (FilterModel filter in list) { WriteableBitmap writeableBitmap = new WriteableBitmap(side, side); foreach (IFilter f in filter.Components) { session.AddFilter(f); } Windows.Foundation.IAsyncAction action = session.RenderToBitmapAsync(writeableBitmap.AsBitmap()); i++; if (i % 10 == 0) { // async, give control back to UI before proceeding. await action; } else { // synchroneous, we keep the CPU for ourselves. Task task = action.AsTask(); task.Wait(); } PhotoThumbnail photoThumbnail = new PhotoThumbnail() { Bitmap = writeableBitmap, Text = filter.Name, Width = side, Margin = new Thickness(6) }; photoThumbnail.Tap += (object sender, System.Windows.Input.GestureEventArgs e) => { App.PhotoModel.ApplyFilter(filter); App.PhotoModel.Dirty = true; NavigationService.GoBack(); }; panel.Children.Add(photoThumbnail); session.UndoAll(); } } }
public async Task AddNewContact(string newContactEmail, string newContactDisplayName = "") { if (newContactEmail == "") { throw new ArgumentNullException("Contact email is empty"); } if (newContactDisplayName == "") { newContactDisplayName = newContactEmail; } await Task.Run(() => { switch (MsnpVersion) { case "MSNP12": TransactionId++; nsSocket.SendCommand($"ADC {TransactionId} FL N={newContactEmail} F={newContactDisplayName}\r\n"); Windows.Foundation.IAsyncAction adcTask = Windows.ApplicationModel.Core.CoreApplication.MainView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { Contact newContact = new Contact((int)ListNumbers.Forward + (int)ListNumbers.Allow) { DisplayName = newContactDisplayName, Email = newContactEmail }; ContactList.Add(newContact); ContactsInForwardList.Add(newContact); }); break; case "MSNP15": TransactionId++; soapRequests.AbContactAdd(newContactEmail); string contactPayload = ReturnXMLNewContactPayload(newContactEmail); int payloadLength = Encoding.UTF8.GetBytes(contactPayload).Length; nsSocket.SendCommand($"ADL {TransactionId} {payloadLength}\r\n{contactPayload}"); Windows.Foundation.IAsyncAction adlTask = Windows.ApplicationModel.Core.CoreApplication.MainView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { Contact newContact = new Contact((int)ListNumbers.Forward + (int)ListNumbers.Allow) { DisplayName = newContactDisplayName, Email = newContactEmail }; ContactList.Add(newContact); ContactsInForwardList.Add(newContact); }); break; default: throw new Exceptions.VersionNotSelectedException(); } }); }
public void FillReverseListCollection() { foreach (Contact contact in ContactList) { if ((contact.OnReverse || contact.Pending) && !contact.OnForward) { Windows.Foundation.IAsyncAction task = Windows.ApplicationModel.Core.CoreApplication.MainView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { ContactsInPendingOrReverseList.Add(contact); }); } } }
void StartRenderLoop() { // If the render loop is already running then do not start another thread. if (_renderLoopWorker != null && _renderLoopWorker.Status == Windows.Foundation.AsyncStatus.Started) { return; } // Create a task for rendering that will be run on a background thread. var workItemHandler = new Windows.System.Threading.WorkItemHandler((Windows.Foundation.IAsyncAction action) => { lock (_renderSurfaceLock) { _eglContext.MakeCurrent(_renderSurface); int oldPanelWidth = -1; int oldPanelHeight = -1; while (action.Status == Windows.Foundation.AsyncStatus.Started) { int panelWidth = 0; int panelHeight = 0; GetSwapChainPanelSize(out panelWidth, out panelHeight); if (panelWidth != oldPanelWidth || panelHeight != oldPanelHeight) { _baseMapView.OnSurfaceChanged(panelWidth, panelHeight); oldPanelWidth = panelWidth; oldPanelHeight = panelHeight; } _baseMapView.OnDrawFrame(); // The call to eglSwapBuffers might not be successful (i.e. due to Device Lost) // If the call fails, then we must reinitialize EGL and the GL resources. if (!_eglContext.SwapBuffers(_renderSurface)) { // XAML objects like the SwapChainPanel must only be manipulated on the UI thread. var worker = _swapChainPanel.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(() => { RecoverFromLostDevice(); })); worker.Close(); return; } _swapChainEvent.WaitOne(); _swapChainEvent.Reset(); } } }); // Run task on a dedicated high priority background thread. _renderLoopWorker = Windows.System.Threading.ThreadPool.RunAsync(workItemHandler, Windows.System.Threading.WorkItemPriority.Normal, Windows.System.Threading.WorkItemOptions.TimeSliced); }
/// <summary> /// Cancels posted PropertyChanged events if it is cancellable. /// This method must be called on the thread that the Dispatcher is associated with. /// </summary> protected virtual void CancelPostPropertyChanged() { if (_invokeAction == null) { return; } #if NICENIS_UWP _invokeAction.Cancel(); #else _invokeAction.Abort(); #endif _invokeAction = null; }
public async Task AcceptNewContact(Contact contactToAccept) { if (contactToAccept == null) { throw new ArgumentNullException("Contact is null"); } if (contactToAccept.OnForward) { return; } await Task.Run(() => { switch (MsnpVersion) { case "MSNP12": TransactionId++; nsSocket.SendCommand($"ADC {TransactionId} FL N={contactToAccept.Email} F={contactToAccept.DisplayName}\r\n"); contactToAccept.OnForward = true; Windows.Foundation.IAsyncAction adc_task = Windows.ApplicationModel.Core.CoreApplication.MainView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { ContactsInForwardList.Add(contactToAccept); ContactsInPendingOrReverseList.Remove(contactToAccept); }); break; case "MSNP15": TransactionId++; soapRequests.AbContactAdd(contactToAccept.Email); string contactPayload = ReturnXMLNewContactPayload(contactToAccept.Email); int payloadLength = Encoding.UTF8.GetBytes(contactPayload).Length; nsSocket.SendCommand($"ADL {TransactionId} {payloadLength}\r\n{contactPayload}"); TransactionId++; contactPayload = ReturnXMLNewContactPayload(contactToAccept.Email, 2); payloadLength = Encoding.UTF8.GetBytes(contactPayload).Length; nsSocket.SendCommand($"ADL {TransactionId} {payloadLength}\r\n{contactPayload}"); contactToAccept.OnForward = true; Windows.Foundation.IAsyncAction adl_task = Windows.ApplicationModel.Core.CoreApplication.MainView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { contactToAccept.DisplayName = contactToAccept.Email; ContactsInForwardList.Add(contactToAccept); ContactsInPendingOrReverseList.Remove(contactToAccept); }); break; default: throw new Exceptions.VersionNotSelectedException(); } }); }
public override void Start() { #if UNITY_WSA_10_0 && !UNITY_EDITOR switch (Priority) { case UniThreadPriority.Normal: _async = Windows.System.Threading.ThreadPool.RunAsync((workItem) => { RunThreadLoop(); }); break; case UniThreadPriority.Low: _async = Windows.System.Threading.ThreadPool.RunAsync((workItem) => { RunThreadLoop(); }, Windows.System.Threading.WorkItemPriority.Low); break; case UniThreadPriority.High: _async = Windows.System.Threading.ThreadPool.RunAsync((workItem) => { RunThreadLoop(); }, Windows.System.Threading.WorkItemPriority.High); break; } #endif }
// init() is called during startup. Initializes locks and condition variables // and launches all threads sending them immediately to sleep. internal static void init() { int requested = int.Parse(OptionMap.Instance["Threads"].v); ManualResetEvent[] initEvents = new ManualResetEvent[requested + 1]; for (int i = 0; i < (requested + 1); i++) { initEvents[i] = new ManualResetEvent(false); } #if WINDOWS_RT Windows.Foundation.IAsyncAction action = Windows.System.Threading.ThreadPool.RunAsync(delegate { launch_threads(initEvents); }, WorkItemPriority.Normal); #else ThreadPool.QueueUserWorkItem(new WaitCallback(launch_threads), initEvents); #endif WaitHandle.WaitAll(initEvents); }
public void HandlePrp() { string[] prpParameters = currentResponse.Split(" "); Windows.Foundation.IAsyncAction task = Windows.ApplicationModel.Core.CoreApplication.MainView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { if (prpParameters[1] == "MFN") { string displayName = plusCharactersRegex.Replace(prpParameters[2], ""); UserInfo.DisplayName = displayName; } else if (prpParameters[2] == "MFN") { string displayName = plusCharactersRegex.Replace(prpParameters[3], ""); UserInfo.DisplayName = displayName; } }); }
/// <summary> /// Raises changed events for the posted property names. /// This method must be called on the thread that the Dispatcher is associated with. /// </summary> private void RaiseEventsForPostedPropertyNames() { Debug.Assert(_invokeAction != null); _invokeAction = null; if (_postedPropertyNames == null) { return; } foreach (var propertyName in _postedPropertyNames) { OnPropertyChanged(propertyName); } _postedPropertyNames.Clear(); }
protected async void LoadContentBackground(Windows.Foundation.IAsyncAction action) { var task = readJson("global"); task.Wait(); var content = task.Result; try { JsonObject config = (JsonObject)JsonObject.Parse(content); ConfigurationManager.LoadConfiguration(config); } catch (Exception e) { } // Load the player resources Rectangle titleSafeArea = GraphicsDevice.Viewport.TitleSafeArea; var playerPosition = new Vector2(titleSafeArea.X, titleSafeArea.Y + titleSafeArea.Height / 2); Texture2D playerTexture = Content.Load <Texture2D>("Graphics\\shipAnimation"); Animation playerAnimation = new Animation(); playerAnimation.Initialize(playerTexture, playerPosition, 115, 69, 8, 30, Color.White, 1, true); _player.Initialize(this, playerAnimation, playerPosition); // load the enemy texture. enemyTexture = Content.Load <Texture2D>("Graphics\\mineAnimation"); // load th texture to serve as the laser. laserTexture = Content.Load <Texture2D>("Graphics\\laser"); // Load the exploision sprite strip explosionTexture = Content.Load <Texture2D>("Graphics\\explosion"); laserSoundEffect = Content.Load <SoundEffect>("Sounds\\laserFire"); await Task.Delay(4000); Loaded = true; }
public void Start() { var uri = this.url; UcwaAppOperationResult result; workItem = Windows.System.Threading.ThreadPool.RunAsync( async(workItemHandler) => { while (!string.IsNullOrWhiteSpace(uri)) { if (workItem.Status == Windows.Foundation.AsyncStatus.Canceled) { break; } // Make pending-Get request result = await this.Transport.GetResourceAsync(uri); if (result.StatusCode == HttpStatusCode.OK) { uri = GetNextEventUri(result.Resource); HandleEvent(result.Resource); } else { HandleException(result); } } }, Windows.System.Threading.WorkItemPriority.Normal ); workItem.Completed += new Windows.Foundation.AsyncActionCompletedHandler( (Windows.Foundation.IAsyncAction source, Windows.Foundation.AsyncStatus status) => { if (workItem.Status == Windows.Foundation.AsyncStatus.Canceled) { return; } if (OnEventChannelClosed != null) { OnEventChannelClosed(status); } }); }
public void HandleNln() { //gets the parameters, does a LINQ query in the contact list and sets the contact's status string[] nlnParameters = currentResponse.Split(" "); string status = nlnParameters[1]; string email = nlnParameters[2]; string displayName = ""; switch (MsnpVersion) { case "MSNP12": displayName = nlnParameters[3]; break; case "MSNP15": displayName = nlnParameters[4]; break; default: throw new Exceptions.VersionNotSelectedException(); } displayName = plusCharactersRegex.Replace(displayName, ""); Windows.Foundation.IAsyncAction task = Windows.ApplicationModel.Core.CoreApplication.MainView.Dispatcher.RunAsync(CoreDispatcherPriority.High, () => { var contactsWithPresence = from contact in ContactList where contact.Email == email select contact; foreach (Contact contact in contactsWithPresence) { contact.PresenceStatus = status; contact.DisplayName = displayName; DatabaseAccess.UpdateContact(UserInfo.Email, contact); } var contactsWithPresenceInForwardList = from contact in ContactsInForwardList where contact.Email == email select contact; foreach (Contact contact in contactsWithPresenceInForwardList) { contact.PresenceStatus = status; contact.DisplayName = displayName; } }); }
/// <summary> /// 根据记录给每个方块面板中的方块绘制颜色。 /// </summary> /// <param name="entries">分级后条目列表</param> /// <param name="haveProgressBoard">是否开启进度条面板,true 为开启,反之不开启</param> private void DrawRectangleColor(TioSalamanca[] entries, bool haveProgressBoard) { IDictionary <int, SolidColorBrush> colorDic = ClassifyColorByLevelScore(entries.Length); Windows.Foundation.IAsyncAction action = Windows.System.Threading.ThreadPool.RunAsync( async(asyncAction) => { GusFring gusFring = new GusFring(entries, colorDic); await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync( priority: Windows.UI.Core.CoreDispatcherPriority.Normal, agileCallback: () => { foreach (Canvas canvas in this.StackCanvas.Children) { if (haveProgressBoard) { ProgressBoard.SlideOn(canvas, new ProgressBoard()); } foreach (var item in canvas.Children) // 过滤掉非 Rectangle 的元素(比如 ProgressBoard 和 DateTag) { if (item is Rectangle rect) { #if DEBUG (int Level, BigInteger Total, SolidColorBrush Color) = gusFring[rect.Name]; rect.Fill = Color; ToolTip toolTip = new ToolTip { Content = rect.Name + $" Level:{Level} Total:{Total} Color:{Color}" }; ToolTipService.SetToolTip(rect, toolTip); #endif #if DEBUG == false rect.Fill = gusFring[rect.Name]; ToolTip toolTip = new ToolTip { Content = rect.Name }; ToolTipService.SetToolTip(rect, toolTip); #endif _rectangleRegisteTable.Add(rect); } } } }); }); }
public void HandleAdc() { string[] adcParameters = currentResponse.Split(" "); string email, displayName; email = adcParameters[3].Replace("N=", ""); displayName = adcParameters[4].Replace("F=", ""); displayName = plusCharactersRegex.Replace(displayName, ""); if (adcParameters[2] == "RL") { var contactsInList = from contactInList in ContactList where contactInList.Email == email select contactInList; if (!contactsInList.Any()) { Contact newContact = new Contact((int)ListNumbers.Reverse) { Email = email, DisplayName = displayName }; ContactList.Add(newContact); Windows.Foundation.IAsyncAction task = Windows.ApplicationModel.Core.CoreApplication.MainView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { ContactsInPendingOrReverseList.Add(newContact); }); ShowNewContactToast(newContact); } else { foreach (Contact contact in contactsInList) { contact.OnReverse = true; Windows.Foundation.IAsyncAction task = Windows.ApplicationModel.Core.CoreApplication.MainView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { ContactsInPendingOrReverseList.Add(contact); }); ShowNewContactToast(contact); } } } }
/// <summary> /// Posts an action that raises changed events for the posted property names if required. /// This method must be called on the thread that the Dispatcher is associated with. /// </summary> private void PostActionIfRequired() { if (_invokeAction != null) { return; } #if NICENIS_UWP _invokeAction = Dispatcher.RunAsync ( priority: PostDispatcherPriority, agileCallback: RaiseEventsForPostedPropertyNames ); #else _invokeAction = Dispatcher.InvokeAsync ( callback: RaiseEventsForPostedPropertyNames, priority: PostDispatcherPriority ); #endif }
/// <summary> /// Sends a batch of events to device hub /// </summary> /// <returns>The task containing the event</returns> public AsyncTask SendEventBatchAsync(IEnumerable <Message> messages) { #if !WINDOWS_UWP if (this.impl == null) { return(AsyncTask.Run(async() => { await this.EnsureOpenedAsync(); await this.impl.SendEventBatchAsync(messages).AsTaskOrAsyncOp(); })); } else { #endif return(this.impl.SendEventBatchAsync(messages).AsTaskOrAsyncOp()); #if !WINDOWS_UWP } #endif }
/// <summary> /// Sends an event to device hub /// </summary> /// <returns>The message containing the event</returns> public AsyncTask SendEventAsync(Message message) { #if !WINDOWS_UWP if (this.impl == null) { return(AsyncTask.Run(async() => { await this.EnsureOpenedAsync(); await this.impl.SendEventAsync(message); })); } else { #endif return(this.impl.SendEventAsync(message).AsTaskOrAsyncOp()); #if !WINDOWS_UWP } #endif }
/// <summary> /// Deletes a received message from the device queue and indicates to the server that the message could not be processed. /// </summary> /// <returns>The previously received message</returns> public AsyncTask RejectAsync(string lockToken) { #if !WINDOWS_UWP if (this.impl == null) { return(AsyncTask.Run(async() => { await this.EnsureOpenedAsync(); await this.impl.RejectAsync(lockToken).AsTaskOrAsyncOp(); })); } else { #endif return(this.impl.RejectAsync(lockToken).AsTaskOrAsyncOp()); #if !WINDOWS_UWP } #endif }
/// <summary> /// Receive a message from the device queue with the specified timeout /// </summary> /// <returns>The receive message or null if there was no message until the specified time has elapsed</returns> public AsyncTaskOfMessage ReceiveAsync(TimeSpan timeout) { #if !WINDOWS_UWP if (this.impl == null) { return(AsyncTask.Run(async() => { await this.EnsureOpenedAsync(); return await this.impl.ReceiveAsync(timeout); })); } else { #endif return(this.impl.ReceiveAsync(timeout).AsTaskOrAsyncOp()); #if !WINDOWS_UWP } #endif }
internal Thread(ThreadLoopType lt, ManualResetEvent initEvent) { is_searching = do_exit = false; maxPly = splitPointsCnt = 0; curSplitPoint = null; loopType = lt; idx = Threads.size(); do_sleep = loopType != ThreadLoopType.Main; // Avoid a race with start_searching() for (int j = 0; j < Constants.MAX_SPLITPOINTS_PER_THREAD; j++) { splitPoints[j] = new SplitPoint(); } #if WINDOWS_RT Windows.Foundation.IAsyncAction action = Windows.System.Threading.ThreadPool.RunAsync(delegate { StartThread(initEvent); }, WorkItemPriority.Normal); #else ThreadPool.QueueUserWorkItem(this.StartThread, initEvent); #endif }
/// <summary> /// Puts a received message back onto the device queue /// </summary> /// <returns>The lock identifier for the previously received message</returns> public AsyncTask AbandonAsync(Message message) { #if !WINDOWS_UWP && !PCL if (this.impl == null) { return(AsyncTask.Run(async() => { await this.EnsureOpenedAsync(); await this.impl.AbandonAsync(message).AsTaskOrAsyncOp(); })); } else { #endif return(this.impl.AbandonAsync(message).AsTaskOrAsyncOp()); #if !WINDOWS_UWP && !PCL } #endif }
static private void StepTicThread(Windows.Foundation.IAsyncAction action) { //This thread runs on a high priority task and loops forever while (true) { bool workPerformed = false; if (IsDriverEnabled) { foreach (Pump p in Pumps) { if (p.DoStep) { p.PinHigh(); } } StepDelay(); foreach (Pump p in Pumps) { if (p.DoStep) { p.PinLow(); p.Steps--; workPerformed = true; } } StepDelay(); //if (ProgressBar != null && ProgressBar.Value < ProgressBar.Maximum) //{ // ProgressBar.Value++; //} if (!workPerformed) { DisableMotorDrivers(); } } } }
public virtual void start0() { action = Windows.System.Threading.ThreadPool.RunAsync((source) => { runImplInternal(); }, priority); action.Completed = new Windows.Foundation.AsyncActionCompletedHandler( (Windows.Foundation.IAsyncAction asyncInfo, Windows.Foundation.AsyncStatus asyncStatus) => { threadMap.TryRemove(thisId, out removedThreadInstance); }); // global::System.Threading.Tasks.Task.Run(() => { internalThread.Start(); }).ConfigureAwait(false).GetAwaiter().GetResult(); // global::System.Diagnostics.Debug.WriteLine("start0() :" + internalThread.Id + " fffff :" + _fthreadId + " state " + internalThread.Status); }
private void speak_Click(object sender, RoutedEventArgs e) { string lang=""; if (tb.Text == "") { if (RE.IsChecked == true) { tb.Text = "Enter Something Here"; } else if (RF.IsChecked == true) { tb.Text = "Entrez quelque chose ici"; } else if (RS.IsChecked == true) { tb.Text = "Escriba algo aquí"; } else if (RG.IsChecked == true) { tb.Text = "Geben Sie hier etwas"; } } else { if (RE.IsChecked == true) { lang = "en"; } else if (RF.IsChecked == true) { lang = "fr"; } else if (RS.IsChecked == true) { lang = "es"; } else if (RG.IsChecked == true) { lang = "de"; } if (Male.IsChecked == true) { IEnumerable<VoiceInformation> voices = from voice in InstalledVoices.All where voice.Language.Substring(0,2).Equals(lang) && voice.Gender.Equals(VoiceGender.Male) select voice; try { spk.SetVoice(voices.ElementAt(0)); }catch(System.InvalidOperationException){} catch(System.ArgumentOutOfRangeException){}; } else if(Female.IsChecked == true) { IEnumerable<VoiceInformation> voices = from voice in InstalledVoices.All where voice.Language.Substring(0,2).Equals(lang) && voice.Gender.Equals(VoiceGender.Female) select voice; try { spk.SetVoice(voices.ElementAt(0)); } catch (System.InvalidOperationException) {} catch (System.ArgumentOutOfRangeException) { }; } task=spk.SpeakTextAsync(tb.Text); task.AsTask(); } }
public void Start() { task = ThreadPool.RunAsync(OnAction); }