Example #1
0
        private void card_CardInserted(object sender, EventArgs e)
        {
            context.Post(new System.Threading.SendOrPostCallback(o =>
            {
                try
                {
                    Console.WriteLine("==================");
                    Console.WriteLine("Inserted Card Info");
                    Console.WriteLine("==================");
                    this.ShowCardInfo();

                    acr123u.connectDirect();
                    acr123u.LCDBacklightControl(0xFF);
                    this.SetLCDDisplayText("Processing ...");
                    this.LEDStatus  = LEDOrange;
                    this.LEDStatus |= LEDAntBlue;
                    this.LEDStatus |= LEDAntGreen;
                    this.LEDStatus |= LEDAntRed;
                    this.acr123u.setLEDControl(this.LEDStatus);
                    acr123u.disconnect();

                    this.cashier.UIDCard = this.GetCardNumber();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }), null);
        }
Example #2
0
        private void card_CardInserted(object sender, EventArgs e)
        {
            context.Post(new System.Threading.SendOrPostCallback(o =>
            {
                try
                {
                    Console.WriteLine("==================");
                    Console.WriteLine("Inserted Card Info");
                    Console.WriteLine("==================");
                    this.ShowCardInfo();

                    acr123u.connectDirect();
                    acr123u.LCDBacklightControl(0xFF);
                    this.SetLCDDisplayText(Constant.MESSAGE_PROCESSING);
                    this.LEDStatus  = Constant.LED_ORANGE;
                    this.LEDStatus |= Constant.LED_ANT_BLUE;
                    this.LEDStatus |= Constant.LED_ANT_GREEN;
                    this.LEDStatus |= Constant.LED_ANT_RED;
                    this.acr123u.setLEDControl(this.LEDStatus);
                    acr123u.disconnect();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }), null);
        }
Example #3
0
        /// <summary>
        /// 发布客户端套接字事件
        /// </summary>
        /// <param name="ServerName"></param>
        private void onClient(AutoCSer.Deploy.OnClientParameter parameter)
        {
            switch (parameter.Type)
            {
            case AutoCSer.Net.TcpServer.ClientSocketEventParameter.EventType.SetSocket:
                context.Post(onClient, true);
                return;

            case AutoCSer.Net.TcpServer.ClientSocketEventParameter.EventType.SocketDisposed:
                context.Post(onClient, false);
                return;
            }
        }
Example #4
0
        public void Post(
            Action action,
            string memberName = null,
            string filePath   = null,
            int lineNumber    = 0)
        {
            AssertArg.IsNotNull(action, nameof(action));
            EnsureInitialized();

            Action wrapper = GetWrappedAction(
                action, null, false,
                memberName, filePath, lineNumber);

            Context.Post(state => wrapper(), null);
        }
Example #5
0
 public void Show(string title, string text, int duration)
 {
     _syncContext.Post(delegate
     {
         ShowCore(title, text, duration);
     }, null);
 }
        public static void Create(System.Threading.SynchronizationContext scontext, Office.IRibbonUI ribbonUI)
        {
            scontext.Post((o) =>
            {
                var hwnd = BackStageTool.GetActiveWindowHwnd();
                if (hwnd != IntPtr.Zero)
                {
                    lock (dic)
                    {
                        CustomPrintBackstageWindow w;
                        if (!dic.TryGetValue(hwnd, out w))
                        {
                            w = new CustomPrintBackstageWindow();
                            w.AssignHandle(BackStageTool.GetActiveWindowHwnd());
                            w.scontext  = scontext;
                            w.ribbonUI  = ribbonUI;
                            w.inspector = Globals.ThisAddIn.Application.ActiveInspector() as Microsoft.Office.Interop.Outlook.Inspector;
                            w.mail      = w.inspector.CurrentItem as Microsoft.Office.Interop.Outlook.MailItem;
                            if (w.mail != null)
                            {
                                w.Page.Html = w.mail.HTMLBody;
                            }

                            dic.Add(hwnd, w);
                        }
                    }
                }
            }, null);
        }
 private void UpdateStatus(string value)
 {
     synchronizationContext.Post(new System.Threading.SendOrPostCallback(o =>
     {
         tbStatus.Text = String.Format("Status: {0}", o);
     }), value);
 }
Example #8
0
        //プロパティーの変更を通知するイベントを発生させる関数
        protected void RaisePropertyChanged([CallerMemberName] string propertyName = null)
        {
            if (PropertyChanged != null)
            {
                if (SynchronizationContext != null)
                {
                    SynchronizationContext.Post(o =>
                    {
                        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
                    }, null);
                }
                else if (GlobalContext != null)
                {
                    GlobalContext.Post(o =>
                    {
                        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
                    }, null);
                }
                else
                {
                    Console.WriteLine("You should set GlobalContext to avoid ui crashing");
                }
            }

            UnsafePropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
Example #9
0
        private async void SaveClip_Click(object sender, RoutedEventArgs e)
        {
            Windows.Storage.Pickers.FileSavePicker fileSavePicker = new Windows.Storage.Pickers.FileSavePicker();
            fileSavePicker.FileTypeChoices.Add("MP4 files", new List <string>()
            {
                ".mp4"
            });
            fileSavePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.VideosLibrary;

            var file = await fileSavePicker.PickSaveFileAsync();

            if (file == null)
            {
                return;
            }

            btnSave.Visibility      = Visibility.Collapsed;
            progressRing.Visibility = Visibility.Visible;
            tbProgress.Visibility   = Visibility.Visible;

            var render = mediaComposition.RenderToFileAsync(file, MediaTrimmingPreference.Precise);

            render.Progress = new AsyncOperationProgressHandler <Windows.Media.Transcoding.TranscodeFailureReason, double>((reson, value) =>
            {
                SynchronizationContext.Post((param) =>
                {
                    tbProgress.Text = value.ToString("0.00") + "%";
                }, null);
            });
            render.Completed = new AsyncOperationWithProgressCompletedHandler <Windows.Media.Transcoding.TranscodeFailureReason, double>((reason, status) =>
            {
                string msg = "Successful";

                var re = reason.GetResults();
                if (re != Windows.Media.Transcoding.TranscodeFailureReason.None || status != AsyncStatus.Completed)
                {
                    msg = "Unsuccessful";
                }
                SynchronizationContext.Post((param) =>
                {
                    btnSave.Visibility      = Visibility.Visible;
                    progressRing.Visibility = Visibility.Collapsed;
                    tbProgress.Visibility   = Visibility.Collapsed;
                    tbProgress.Text         = msg;
                }, null);
            });
        }
Example #10
0
 protected void BeginInvoke(Action action)
 {
     if (action == null)
     {
         return;
     }
     _context.Post(i => action.Invoke(), null);
 }
Example #11
0
 public void functionargumentsPopup()
 {
     xlcontext_.Post(
         delegate(object state)
     {
         range_.FunctionWizard();
     }, null);
 }
    //private MyEvent clicked;

    //event MyEvent Itest.Clicked
    //{
    //    add
    //    {
    //        clicked += value;
    //    }
    //    remove
    //    {
    //        clicked -= value;
    //    }
    //}


    protected override void OnConnectionClosed(EventArgs e)
        {
            // m_SynchronizingObject IsNot Nothing Then
            if (m_synchronizationContext != null)
            {
                try
                {
                    m_synchronizationContext.Post(ConnectionClosedSync, EventArgs.Empty);
                }
                catch (Exception )
                {
                }
            }
            else
            {
                base.OnConnectionClosed(e);
            }
        }
        void StoneOrderVMObject_SetStoneOrderExceptionFinished(bool obj)
        {
            try
            {
                if (obj)
                {
                    App.UserVMObject.AsyncGetPlayerInfo();

                    _syn.Post(o =>
                    {
                        this.Close();
                    }, null);
                }
            }
            catch (Exception exc)
            {
                MyMessageBox.ShowInfo("购买矿石,申诉订单回调处理异常。" + exc.Message);
            }
        }
Example #14
0
 private void continuousSearch()
 {
     // The sprinkled thread sleeps is for mono 3.x
     // winforms stuff freaking out
     while (_runSearch)
     {
         if (_lastKeypress.AddMilliseconds(400) > DateTime.Now || _searchTerms.Count == 0)
         {
             System.Threading.Thread.Sleep(50);
             continue;
         }
         var searchText = "";
         while (_searchTerms.Count > 0)
         {
             searchText = _searchTerms.Dequeue();
         }
         try
         {
             var items = _cache.Find(searchText).Take(30).ToList();
             if (items.Count > 30)
             {
                 items = items.GetRange(0, 30);
             }
             _syncContext.Post(nothing => informationList.Items.Clear(), null);
             foreach (var item in items)
             {
                 _syncContext.Post(itm => addItem((ICodeReference)itm), item);
             }
             _syncContext.Post(nothing => {
                 if (informationList.Items.Count > 0)
                 {
                     informationList.Items[0].Selected = true;
                 }
                 informationList.Refresh();
             }, items);
         }
         catch (Exception ex)
         {
             Console.WriteLine(ex.ToString());
         }
     }
 }
Example #15
0
 public override void Stop()
 {
     if (m_timer != null)
     {
         m_timer.Stop();
         m_timer.Dispose();
         m_timer = null;
         m_syncContext.Post(PostEvent, false);
         m_scheduleState = ScheduleState.None;
     }
 }
 public void dowork()
 {
     string[] retval = System.IO.Directory.GetFiles(@"C:\Windows\System32", "*.*", System.IO.SearchOption.TopDirectoryOnly);
     foreach (var item in retval)
     {
         System.Threading.Thread.Sleep(25);
         _SynchronizationContext.Post(new System.Threading.SendOrPostCallback(delegate(object obj)
         {
             OnMessageReceivedEvent(item);
         }), null);
     }
 }
Example #17
0
        /// <summary>
        /// Schedules the continuation onto the <see cref="Task"/> associated with this <see cref="TaskAwaiter"/>.
        /// </summary>
        /// <param name="task">The awaited task.</param>
        /// <param name="continuation">The action to invoke when the await operation completes.</param>
        /// <param name="continueOnCapturedContext">Whether to capture and marshal back to the current context.</param>
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="continuation"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="NullReferenceException">The awaiter was not properly initialized.</exception>
        /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
        internal static void OnCompletedInternal(Task task, Action continuation, bool continueOnCapturedContext)
        {
            if (continuation == null)
            {
                throw new ArgumentNullException("continuation");
            }

            SynchronizationContext sc = continueOnCapturedContext ? SynchronizationContext.Current : null;

            if (sc != null && sc.GetType() != typeof(SynchronizationContext))
            {
                task.ContinueWith(param0 =>
                {
                    try
                    {
                        sc.Post(state => ((Action)state).Invoke(), continuation);
                    }
                    catch (Exception exception)
                    {
                        AsyncServices.ThrowAsync(exception, null);
                    }
                });//, CancellationToken.None);, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
                return;
            }

            TaskScheduler taskScheduler = Task.DefaultScheduler;

            if (task.IsCompleted)
            {
                //Task.Factory.StartNew(s => ((Action)s).Invoke(), continuation, CancellationToken.None, TaskCreationOptions.None, taskScheduler);
                continuation();
                return;
            }

            //if (taskScheduler != TaskScheduler.Default)
            //{
            //    task.ContinueWith(_ => RunNoException(continuation), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, taskScheduler);
            //    return;
            //}

            task.ContinueWith(param0 =>
            {
                if (IsValidLocationForInlining)
                {
                    RunNoException(continuation);
                    return;
                }

                //Task.Factory.StartNew(s => RunNoException((Action)s), continuation, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
                continuation();
            });//, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
        }
Example #18
0
 /// <summary>
 /// Show a banner notification with the given data
 /// </summary>
 /// <param name="data"></param>
 public void ShowNotification(BannerData data)
 {
     // Execute the banner in the context of the UI thread
     syncContext.Post((d) =>
     {
         if (banner == null)
         {
             banner           = new BannerForm();
             banner.Disposed += (s, e) => banner = null;
         }
         banner.SetData(data);
     }, null);
 }
Example #19
0
        private void OnTimerElapsed(object sender, ElapsedEventArgs e)
        {
            timer.Stop();

            if (synchronizationContext == null)
            {
                propertyValueChangeAction?.Invoke(propertyName, oldValue, newValue);
            }
            else
            {
                synchronizationContext.Post(state => propertyValueChangeAction?.Invoke(propertyName, oldValue, newValue), null);
            }
        }
Example #20
0
        protected void NoteMessagesAdded()
        {
            bool seqNumsWereTheSameOnEntry = (seqNumGenNoteMessagesAdded.VolatileValue == seqNumDistributedUpdateCalls);

            seqNumGenNoteMessagesAdded.IncrementSkipZero();

            if (seqNumsWereTheSameOnEntry || distributeUpdateCallsAnywayTimer.IsTriggered)
            {
                System.Threading.SynchronizationContext defaultSC = LogMessageObservableCollection.DefaultSynchronizationContext;
                if (defaultSC != null)
                {
                    defaultSC.Post(DistributeUpdateCalls, distributeUpdateCallsMutexNoLongerInUse);       // invoke my DistributeUpdateCalls in the context of LogMessageObservableCollection's SynchronizationContext
                }
            }
        }
Example #21
0
 /// <summary>
 /// Convenience function to consolidate event dispatching boilerplate code.
 /// Events are dispatched on the message queue of a threads' synchronization
 /// context, if possible.
 /// @since 3.0
 /// </summary>
 public static void DispatchOnContext <T>(this EventHandler <T> handler, object sender,
                                          System.Threading.SynchronizationContext context,
                                          T eventArgs) where T : EventArgs
 {
     if (handler != null)
     {
         if (context != null)
         {
             System.Threading.SendOrPostCallback evt = (spc_args) => { handler(sender, spc_args as T); };
             context.Post(evt, eventArgs);
         }
         else
         {
             handler(sender, eventArgs);
         }
     }
 }
 protected void OnDataReceived(GenericTcpEventArgs e)
 {
     if (m_synchronizationContext != null)
     {
         try
         {
             m_synchronizationContext.Post(DataReceivedSync, e);
         }
         catch
         {
         }
     }
     else
     {
         if (DataReceived != null)
         {
             DataReceived(this, e);
         }
     }
 }
Example #23
0
 public static SqlConnection AddMessagesManagement(this SqlConnection con,
                                                   System.Threading.SynchronizationContext SyncContext, EventHandler <SqlMessageEventArgs> InfoMessage)
 {
     if (SyncContext == null)
     {
         return(con);
     }
     if (con.FireInfoMessageEventOnUserErrors)
     {
         return(con);
     }
     con.FireInfoMessageEventOnUserErrors = true;
     con.InfoMessage += (s, e) =>
                        SyncContext.Post(_ => InfoMessage?.Invoke(
                                             s, new SqlMessageEventArgs
     {
         Message  = e.Message,
         Progress = e.Errors[0]?.State ?? 0
     }), null);
     return(con);
 }
 private void Server_Received(object sender, DataReceivedEventArgs e)
 {
     context.Post(async s =>
     {
         if (e.CommandType == typeof(PipeCommands.SetSkeletalInputEnable))
         {
             var d = (PipeCommands.SetSkeletalInputEnable)e.Data;
             Settings.Current.EnableSkeletal = d.enable;
             SteamVR2Input.EnableSkeletal    = Settings.Current.EnableSkeletal;
         }
         else if (e.CommandType == typeof(PipeCommands.StartKeyConfig))
         {
             doKeyConfig = true;
             controlWPFWindow.faceController.StartSetting();
             CurrentKeyConfigs.Clear();
         }
         else if (e.CommandType == typeof(PipeCommands.EndKeyConfig))
         {
             controlWPFWindow.faceController.EndSetting();
             doKeyConfig = false;
             CurrentKeyConfigs.Clear();
         }
         else if (e.CommandType == typeof(PipeCommands.StartKeySend))
         {
             doKeySend = true;
             CurrentKeyConfigs.Clear();
         }
         else if (e.CommandType == typeof(PipeCommands.EndKeySend))
         {
             doKeySend = false;
             CurrentKeyConfigs.Clear();
         }
         else if (e.CommandType == typeof(PipeCommands.SetKeyActions))
         {
             var d = (PipeCommands.SetKeyActions)e.Data;
             Settings.Current.KeyActions = d.KeyActions;
         }
     }, null);
 }
        void Client_GetSumLastDayValidStoneStackCompleted(object sender, Wcf.Clients.WebInvokeEventArgs <int> e)
        {
            try
            {
                App.BusyToken.CloseBusyWindow();
                if (e.Error != null)
                {
                    MyMessageBox.ShowInfo("获取工厂昨日总有数矿石机数失败。原因为:" + e.Error.Message);
                    return;
                }

                _syn.Post(o =>
                {
                    StoneFactorySetYesterdayProfitWindow win = new StoneFactorySetYesterdayProfitWindow(Convert.ToInt32(o));
                    win.ShowDialog();

                    App.StoneFactoryVMObject.AsyncGetStoneFactorySystemDailyProfitList(GlobalData.PageItemsCount, 1);
                }, e.Result);
            }
            catch (Exception exc)
            {
                MyMessageBox.ShowInfo("获取工厂昨日总有数矿石机数返回处理异常1。原因为:" + exc.Message);
            }
        }
Example #26
0
        private void BeginAsynchronousSearch(List <WppComputer> computers)
        {
            if (this.SearchComputerProgress != null)
            {
                this.SearchComputerProgress(0, String.Format(this._localization.GetLocalizedString("FoundComputersInAD"), computers.Count));
            }

            System.Threading.SynchronizationContext uiContext = System.Threading.SynchronizationContext.Current;

            this._searcherThread = new System.Threading.Thread(new System.Threading.ThreadStart(() =>
            {
                if (computers.Count != 0)
                {
                    this.SearchComputersInWsus(computers);
                }
                uiContext.Post(new System.Threading.SendOrPostCallback(UpdateDataTable), computers);

                if (this.SearchComputerFinished != null)
                {
                    this.SearchComputerFinished();
                }
            }));
            this._searcherThread.Start();
        }
Example #27
0
        protected void DistributeUpdateCalls(object mutexNoLongerInUse)
        {
            seqNumDistributedUpdateCalls = seqNumGenNoteMessagesAdded.VolatileValue;

            System.Threading.SynchronizationContext currentSC = System.Threading.SynchronizationContext.Current;

            //lock (mutex)    // only run one instance at a time per mutex (blocks later queued calls)
            {
                LogMessageObservableCollection[] activeCollectionSnapshot = LogMessageObservableCollection.InstanceArray;

                foreach (LogMessageObservableCollection lmoc in activeCollectionSnapshot)
                {
                    System.Threading.SynchronizationContext lmocSC = lmoc.SynchronizationContext;
                    if (object.ReferenceEquals(currentSC, lmocSC))
                    {
                        lmoc.Update();
                    }
                    else
                    {
                        lmocSC.Post(lmoc.Update, null); // asynchronous cross thread invoke.  If any of the lmoc instances use a different SC than the default one (construction time one) then just post the update call to its sc.
                    }
                }
            }
        }
Example #28
0
 /// <summary>
 /// POST 调用
 /// </summary>
 public void Post()
 {
     context.Post(onPost, null);
 }
Example #29
0
 public void SendMessage(string message)
 {
     syncContext.Post(new System.Threading.SendOrPostCallback(OnReceived), message);
 }
Example #30
0
 public void BroadcastToClient(EventDataType eventData)
 {
     _syncContext.Post(new System.Threading.SendOrPostCallback(OnBroadcast), eventData);
 }