Post() public method

public Post ( SendOrPostCallback d, object state ) : void
d SendOrPostCallback
state object
return void
        void Client_AddDiamondShoppingItemCompleted(object sender, Wcf.Clients.WebInvokeEventArgs <int> e)
        {
            try
            {
                App.BusyToken.CloseBusyWindow();
                if (e.Error != null)
                {
                    MyMessageBox.ShowInfo("保存钻石商品失败。原因为:" + e.Error.Message);
                    return;
                }

                if (e.Result == OperResult.RESULTCODE_TRUE)
                {
                    MyMessageBox.ShowInfo("保存钻石商品成功");
                    _syn.Post((o) =>
                    {
                        this.Close();
                    }, null);
                }
                else
                {
                    MyMessageBox.ShowInfo("保存钻石商品失败。原因为:" + OperResult.GetMsg(e.Result));
                }
            }
            catch (Exception exc)
            {
                MyMessageBox.ShowInfo("保存钻石商品异常。原因为:" + exc.Message);
            }
        }
        public static void ExecuteGaleryScrape(MainPage mainpage, SynchronizationContext context, Api.Parameter.OverviewParameter parameters = null)
        {
            if (parameters == null)
                parameters = new Api.Parameter.OverviewParameter();

            context.Post((_) =>
            {
                mainpage.SkoftenDataContext.GalleryItemsLoading = true;
            }, null);

            parameters.Type = mainpage.SkoftenDataContext.CurrentGalleryType;

            if (parameters.StartOver)
            {
                mainpage.SkoftenDataContext.GalleryPaging = 0;
                mainpage.SkoftenDataContext.GalleryItemIndex = 0;
                mainpage.SkoftenDataContext.SelectedGallery = 0;
            }


            parameters.Paging = mainpage.SkoftenDataContext.GalleryPaging;

            mainpage.SkoftenDataContext.GalleryPaging += 12;

            OverviewExecute oe = new OverviewExecute();
            oe.Parameters = parameters;
            oe.Execute();
            var result = oe.Result;


            context.Post((_) =>
            {
                if(parameters.StartOver)
                {
                    mainpage.SkoftenDataContext.Gallery.Clear();
                }

                foreach (var item in result)
                {
                    if(parameters.Type == Api.Parameter.OverviewType.EroDump)
                    {
                        if (!item.Url.Contains("babes.skoften.net"))
                        {
                            mainpage.SkoftenDataContext.GalleryItemIndex++;
                            continue;
                        }
                    }

                    item.Index = mainpage.SkoftenDataContext.GalleryItemIndex;
                    mainpage.SkoftenDataContext.Gallery.Add(item);
                    mainpage.SkoftenDataContext.GalleryItemIndex++;
                }

                mainpage.SkoftenDataContext.GalleryItemsLoading = false;
            }, null);
        }
        public PresentationWindow(IMainWindowPresenter dataContext)
        {
            InitializeComponent();
            context = SynchronizationContext.Current;

            // register callbacks for slide control
            dataContext.NextSlide += (o, args) => context.Post(state => NextSlide(), null);
            dataContext.PreviousSlide += (o, pres) => context.Post(state => PreviousSlide(), null);
            dataContext.SwitchPause += (o, pres) => context.Post(state => SwitchPause(), null);
        }
        private async void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            var deviceName = ConfigurationManager.AppSettings["DeviceName"];
            device = PTZDevice.GetDevice(deviceName, PTZType.Relative);

            url = ConfigurationManager.AppSettings["relayServerUrl"];
            remoteGroup = Environment.MachineName; //They have to hardcode the group, but for us it's our machine name
            connection = new HubConnection(url);
            proxy = connection.CreateHubProxy("RelayHub");

            connection.TraceLevel = TraceLevels.StateChanges | TraceLevels.Events;
            connection.TraceWriter = new PTZRemoteTraceWriter(Log);

            //Can't do this here because DirectShow has to be on the UI thread!
            // This would cause an obscure COM casting error with no clue what's up. So, um, ya.
            //proxy.On<int, int>("Move",(x,y) => device.Move(x, y));
            //proxy.On<int>("Zoom", (z) => device.Zoom(z));

            magic = SynchronizationContext.Current;

            proxy.On<int, int>("Move", (x, y) =>
            {
                //Toss this over the fence from this background thread to the UI thread
                magic.Post((_) => {
                    Log(String.Format("Move({0},{1})", x,y));
                    device.Move(x, y);
                }, null);
            });

            proxy.On<int>("Zoom", (z) =>
            {
                magic.Post((_) =>
                {
                    Log(String.Format("Zoom({0})", z));
                    device.Zoom(z);
                }, null);
            });


            try
            {
                await connection.Start();
                Log("After connection.Start()");
                await proxy.Invoke("JoinRelay", remoteGroup);
                Log("After JoinRelay");
            }
            catch (Exception pants)
            {
                Log(pants.GetError().ToString());
                throw;
            }
        }
        public static void ExecuteGaleryScrape(MainPage mainpage, SynchronizationContext context, Api.Parameter.OverviewParameter parameters = null)
        {
            if (parameters == null)
                parameters = new Api.Parameter.OverviewParameter();

            context.Post((_) =>
            {
                mainpage.PageDataContext.GalleryItemsLoading = true;

                if (parameters.StartOver)
                    mainpage.PageDataContext.Gallery.Clear();
            }, null);

            parameters.Category = mainpage.PageDataContext.CurrentArticleGallery;

            if (parameters.StartOver)
            {
                mainpage.PageDataContext.GalleryPaging = -1;
                mainpage.PageDataContext.GalleryItemIndex = 0;
                mainpage.PageDataContext.SelectedGallery = 0;
            }

            mainpage.PageDataContext.GalleryPaging += 1;
            parameters.Paging = mainpage.PageDataContext.GalleryPaging;

            OverviewExecute oe = new OverviewExecute();
            oe.Parameters = parameters;
            oe.Execute();
            var result = oe.Result;


            context.Post((_) =>
            {
                if (parameters.StartOver)
                {
                    mainpage.PageDataContext.Gallery.Clear();
                }

                foreach (var item in result)
                {
                    item.Index = mainpage.PageDataContext.GalleryItemIndex;
                    mainpage.PageDataContext.Gallery.Add(item);
                    mainpage.PageDataContext.GalleryItemIndex++;
                }

                mainpage.PageDataContext.GalleryItemsLoading = false;
            }, null);
        }
        public ToolStripGitStatus()
        {
            syncContext = SynchronizationContext.Current;
            gitGetUnstagedCommand.Exited += (o, ea) => syncContext.Post(_ => onData(), null);

            InitializeComponent();

            Settings.WorkingDirChanged += Settings_WorkingDirChanged;

            GitUICommands.Instance.PreCheckoutBranch += GitUICommands_PreCheckout;
            GitUICommands.Instance.PreCheckoutRevision += GitUICommands_PreCheckout;
            GitUICommands.Instance.PostCheckoutBranch += GitUICommands_PostCheckout;
            GitUICommands.Instance.PostCheckoutRevision += GitUICommands_PostCheckout;

            // Setup a file watcher to detect changes to our files, or the .git repo files. When they
            // change, we'll update our status.
            watcher.Changed += watcher_Changed;
            watcher.Created += watcher_Changed;
            watcher.Deleted += watcher_Changed;
            watcher.Error += watcher_Error;
            watcher.IncludeSubdirectories = true;

            try
            {
                watcher.Path = Settings.WorkingDir;
                watcher.EnableRaisingEvents = true;
            }
            catch { }
            update();
        }
        public ToolStripGitStatus()
        {
            syncContext = SynchronizationContext.Current;
            gitGetUnstagedCommand.Exited += new EventHandler(delegate(object o, EventArgs ea)
                {
                    syncContext.Post(_ => onData(), null);
                });

            InitializeComponent();

            Settings.WorkingDirChanged += new Settings.WorkingDirChangedHandler(Settings_WorkingDirChanged);

            // Setup a file watcher to detect changes to our files, or the .git repo files. When they
            // change, we'll update our status.
            watcher.Changed += new FileSystemEventHandler(watcher_Changed);
            watcher.Created += new FileSystemEventHandler(watcher_Changed);
            watcher.Deleted += new FileSystemEventHandler(watcher_Changed);
            watcher.Error += new ErrorEventHandler(watcher_Error);
            watcher.IncludeSubdirectories = true;

            try
            {
                watcher.Path = Settings.WorkingDir;
                watcher.EnableRaisingEvents = true;
            }
            catch { }
            update();
        }
Beispiel #8
0
        public InboxViewModel(IEmailService emailService, IRegionManager regionManager)
        {
            synchronizationContext = SynchronizationContext.Current ?? new SynchronizationContext();

            _composeMessageCommand = new DelegateCommand<object>(ComposeMessage);
            _replyMessageCommand = new DelegateCommand<object>(ReplyMessage, CanReplyMessage);
            _openMessageCommand = new DelegateCommand<EmailDocument>(OpenMessage);

            messagesCollection = new ObservableCollection<EmailDocument>();
            Messages = new CollectionView(this.messagesCollection);
            Messages.CurrentChanged += (s, e) =>
                _replyMessageCommand.RaiseCanExecuteChanged();

            _emailService = emailService;
            _regionManager = regionManager;

            if (_emailService != null)
            {
                _emailService.BeginGetEmailDocuments(
                    r =>
                        {
                            var messages = _emailService.EndGetEmailDocuments(r);
                            synchronizationContext.Post(
                                s =>
                                    {
                                        foreach (var message in messages)
                                        {
                                            messagesCollection.Add(message);
                                        }
                                    }, null);
                        }, null);
            }
        }
        public ToolStripGitStatus()
        {
            syncContext = SynchronizationContext.Current;
            gitGetUnstagedCommand.Exited += (o, ea) => syncContext.Post(_ => onData(), null);

            InitializeComponent();
            CommitTranslatedString = "Commit";

            Settings.WorkingDirChanged += (_, newDir, newGitDir) => TryStartWatchingChanges(newDir, newGitDir);

            GitUICommands.Instance.PreCheckoutBranch += GitUICommands_PreCheckout;
            GitUICommands.Instance.PreCheckoutRevision += GitUICommands_PreCheckout;
            GitUICommands.Instance.PostCheckoutBranch += GitUICommands_PostCheckout;
            GitUICommands.Instance.PostCheckoutRevision += GitUICommands_PostCheckout;

            // Setup a file watcher to detect changes to our files. When they
            // change, we'll update our status.
            watcher.Changed += watcher_Changed;
            watcher.Created += watcher_Changed;
            watcher.Deleted += watcher_Changed;
            watcher.Error += watcher_Error;
            watcher.IncludeSubdirectories = true;
            watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite;

            // Setup a file watcher to detect changes to the .git repo files. When they
            // change, we'll update our status.
            gitDirWatcher.Changed += gitWatcher_Changed;
            gitDirWatcher.Created += gitWatcher_Changed;
            gitDirWatcher.Deleted += gitWatcher_Changed;
            gitDirWatcher.Error += watcher_Error;
            gitDirWatcher.IncludeSubdirectories = true;
            gitDirWatcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite;

            TryStartWatchingChanges(Settings.WorkingDir, Settings.Module.GetGitDirectory());
        }
Beispiel #10
0
        /// <summary>Throws the exception on the thread pool.</summary>
        /// <param name="exception">The exception to propagate.</param>
        /// <param name="targetContext">
        /// The target context on which to propagate the exception; otherwise, <see langword="null"/> to use the thread
        /// pool.
        /// </param>
        internal static void ThrowAsync(Exception exception, SynchronizationContext targetContext)
        {
            if (targetContext != null)
            {
                try
                {
                    targetContext.Post(
                        state =>
                        {
                            throw PrepareExceptionForRethrow((Exception)state);
                        }, exception);
                    return;
                }
                catch (Exception ex)
                {
                    exception = new AggregateException(exception, ex);
                }
            }

#if NET45PLUS
            Task.Run(() =>
            {
                throw PrepareExceptionForRethrow(exception);
            });
#else
            ThreadPool.QueueUserWorkItem(state =>
            {
                throw PrepareExceptionForRethrow((Exception)state);
            }, exception);
#endif
        }
        /// <summary>Throws the exception on the thread pool.</summary>
        /// <param name="exception">The exception to propagate.</param>
        /// <param name="targetContext">
        /// The target context on which to propagate the exception; otherwise, <see langword="null"/> to use the thread
        /// pool.
        /// </param>
        internal static void ThrowAsync(Exception exception, SynchronizationContext targetContext)
        {
            // If the user supplied a SynchronizationContext...
            if (targetContext != null)
            {
                try
                {
                    // Post the throwing of the exception to that context, and return.
                    targetContext.Post(state => { throw PrepareExceptionForRethrow((Exception)state); }, exception);
                    return;
                }
                catch (Exception postException)
                {
                    // If something goes horribly wrong in the Post, we'll propagate both exceptions on the thread pool
                    exception = new AggregateException(exception, postException);
                }
            }

#if NET45PLUS
            Task.Run(() =>
            {
                throw PrepareExceptionForRethrow(exception);
            });
#else
            // Propagate the exception(s) on the ThreadPool
            ThreadPool.QueueUserWorkItem(state => { throw PrepareExceptionForRethrow((Exception)state); }, exception);
#endif
        }
Beispiel #12
0
 private static CancellableTimout ScheduleInternal(Action action, int delay, SynchronizationContext syncCtx)
 {
     var c = new CancellableTimout();
     c.action = action;
     c.syncCtx = syncCtx;
     var t = new Timer(state =>
     {
         var cc = (CancellableTimout)state;
         var a = cc.action;
         if (a != null)
         {
             if (cc.syncCtx != null)
             {
                 syncCtx.Post(new SendOrPostCallback(z =>
                 {
                     using (cc)
                     {
                         if (cc.action != null) a();
                     }
                 }), null);
                 return;
             }
             else
             {
                 a();
             }
         }
         cc.Dispose();
     }, c, delay, Timeout.Infinite);
     c.timer = t;
     c.delay = delay;
     return c;
 }
Beispiel #13
0
		internal static void ThrowAsync(Exception exception, SynchronizationContext targetContext)
		{
			if (targetContext != null)
			{
				try
				{
					targetContext.Post(delegate(object state)
					{
						throw AsyncServices.PrepareExceptionForRethrow((Exception)state);
					}, exception);
					return;
				}
				catch (Exception ex)
				{
					exception = new AggregateException(new Exception[]
					{
						exception,
						ex
					});
				}
			}
			ThreadPool.QueueUserWorkItem(delegate(object state)
			{
				throw AsyncServices.PrepareExceptionForRethrow((Exception)state);
			}, exception);
		}
Beispiel #14
0
        int DoSign(IEnumerable<Artifact> artifacts, SynchronizationContext sc)
        {
            var restApi = new RallyRestApi(Settings.Default.RallyUser, Settings.Default.RallyPassword
                //, proxy: new WebProxy("localhost:8888", false)
                );

            foreach (var tagArt in artifacts)
            {
                var toCreate = new DynamicJsonObject();
                toCreate["Text"] = "%FIX_CODE_REVIEW_PASSED%";
                toCreate["Artifact"] = tagArt.Reference;
                var createResult = restApi.Create("ConversationPost", toCreate);

                // update status
                sc.Post(_ => {
                    var lvi = listViewArtifacts.Items.Cast<ListViewItem>().FirstOrDefault(l => l.Tag == tagArt);
                    if (!createResult.Success)
                    {
                        lvi.BackColor = Color.Tomato;

                        if (createResult.Errors.Count > 0)
                            lvi.SubItems[1].Text = createResult.Errors[0];
                        else
                            lvi.SubItems[1].Text = "Unexpected error";
                    }
                    else
                    {
                        lvi.BackColor = Color.LightGreen;
                        lvi.SubItems[3].Text = "✔";
                    }
                }, null);
            }

            return 0;
        }
        public void addToLog(string description)
        {
            // The UI thread won't be handling the callback, but it is the only one allowed to update the controls.
            // So, we will dispatch the UI update back to the UI sync context.

            //Create a SendOrPostCallback delegate with an anon method which recieves an Object called state and runs code in the SychronisationContext it is marshalled to using Post
            SendOrPostCallback callback =
                delegate(object state)
            {
                //state is a string object.
                mainForm.updateTextBoxLog(state.ToString());
            };

            //Post takes a delagate and a State object and runs the delegate(State object) in the context Post is called on.
            _uiSyncContext.Post(callback, description);
        }
 /// <summary>
 /// 处理连接关闭事件
 /// </summary>
 /// <param name="e"></param>
 /// <param name="context"></param>
 protected virtual void InvokeConnectionClosed(SocketModuleEventArgs e, SynchronizationContext context)
 {
     if (null != context)
         context.Post(HandlerConnectionClosed, e);
     else
         HandlerConnectionClosed(e);
 }
 public async void CarregaTirinhas()
 {
     synchronizationContext = SynchronizationContext.Current;
     var p = new PostsService();
     var tirinhas = await p.GetPosts(0, tirinha => true);
     foreach (var tirinha in tirinhas)
         synchronizationContext.Post(state => { Tirinhas.Add(tirinha); }, null);
 }
        void GambleStoneVMObject_GambleStoneGetRoundInfoEvent(GambleStoneRoundInfo obj)
        {
            _syn.Post(o =>
            {
                for (int i = 0; i < obj.WinColorItems.Length; i++)
                {
                    BitmapImage bmp = null;
                    switch ((GambleStoneItemColor)obj.WinColorItems[i])
                    {
                    case GambleStoneItemColor.Red:
                        //bmp = new BitmapImage(new Uri(@"../../Resources/gamblered.png", UriKind.Relative));
                        bmp = bmpRed;
                        break;

                    case GambleStoneItemColor.Green:
                        //bmp = new BitmapImage(new Uri(@"../../Resources/gamblegreen.png", UriKind.Relative));
                        bmp = bmpGreen;
                        break;

                    case GambleStoneItemColor.Blue:
                        //bmp = new BitmapImage(new Uri(@"../../Resources/gambleblue.png", UriKind.Relative));
                        bmp = bmpBlue;
                        break;

                    case GambleStoneItemColor.Purple:
                        //bmp = new BitmapImage(new Uri(@"../../Resources/gambleyellow.png", UriKind.Relative));
                        bmp = bmpPurple;
                        break;

                    default:
                        break;
                    }
                    this._WinnedColorItem[i].Source = bmp;
                    if (bmp == null)
                    {
                        this._WinnedColorItem[i].Visibility = System.Windows.Visibility.Collapsed;
                    }
                    else
                    {
                        this._WinnedColorItem[i].Visibility = System.Windows.Visibility.Visible;
                    }
                }

                GC.Collect();
            }, null);
        }
Beispiel #19
0
        static void PrintOnDifferentThread()
        {
            for (int i = 0; i <= 10; i++)
            {
                Console.WriteLine(string.Format("{0}", i.ToString(System.Globalization.NumberFormatInfo.CurrentInfo)));
            }

            _synchObject.Post((x) => { Console.WriteLine("djsfkajdskfjasdlkf"); }, null);
        }
Beispiel #20
0
 private void Update(SynchronizationContext context, CancellationToken token)
 {
     // this loop runs on a worker thread
     while (!token.IsCancellationRequested)
     {
         context.Post(_ => this.UpdatePlot(), null);
         Thread.Sleep(250);
     }
 }
Beispiel #21
0
        public MainWindow()
        {
            InitializeComponent();

            _uiContext = SynchronizationContext.Current;
            _neovim = new NeovimClient(@"C:\Program Files\Neovim\bin\nvim.exe");
            // Event is asynchronous so we need to handle the redraw event in the UI thread
            _neovim.Redraw += (o, args) => _uiContext.Post((x) => NeovimOnRedraw(o, args), null);
            _neovim.ui_attach(_columns, _rows, true);
        }
 protected void InvokeIfRequired(SynchronizationContext context, SendOrPostCallback action)
 {
     if (SynchronizationContext.Current == context)
     {
         action(new Object());
     }
     else
     {
         context.Post(action, new Object());
     }
 }
        public static void ExecuteSingleArticleScrape(MainPage mainpage, SynchronizationContext theContext, OverviewResult search)
        {
            theContext.Post((_) =>
            {
                mainpage.Pivot.SelectedIndex = 1;
                mainpage.PageDataContext.ArticleLoading = true;
                mainpage.PageDataContext.Articles.Clear();
            }, null);

            ArticleExecute execute = new ArticleExecute();
            execute.Parameters.Url = "http://www.trending.nl/" + search.Url;
            execute.Parameters.Type = mainpage.PageDataContext.CurrentArticleGallery;
            execute.Execute();
            var article = execute.Result;

            theContext.Post((_) =>
            {
                mainpage.PageDataContext.InitializeNewArticle(article);
            }, null);
        }
        public static void ExecuteSingleDumpScrape(MainPage mainpage, SynchronizationContext theContext, OverviewResult search)
        {
            theContext.Post((_) =>
            {
                mainpage.Pivot.SelectedIndex = 1;
                mainpage.SkoftenDataContext.DumpItemsLoading = true;
                mainpage.SkoftenDataContext.DumpItems.Clear();
            }, null);

            DumpExecute execute = new DumpExecute();
            execute.Parameters.Url = search.Url;
            execute.Parameters.Type = mainpage.SkoftenDataContext.CurrentGalleryType;
            execute.Execute();
            var dumpItems = execute.Result;

            theContext.Post((_) =>
            {
                mainpage.SkoftenDataContext.InitializeNewDumpList(dumpItems);
            }, null);
        }
Beispiel #25
0
        internal static void SetUiContext(SynchronizationContext synchronizationContext)
        {
            _onUiExec = action =>
            {
                if (_isUiThread)
                    action();
                else
                    synchronizationContext.Post(e => action(), null);
            };

            OnUiThread(() => _isUiThread = true);
        }
Beispiel #26
0
        void OnDownloadComplete(string filename)
        {
            EventHandler <downloadCompleteEventArgs> temp = downloadComplete;

            if (temp != null)
            {
                downloadCompleteEventArgs e = new downloadCompleteEventArgs();
                e.filename = filename;
                context.Post(delegate(object state) { downloadComplete(this, e); }, null);
            }
        }
        public EnableControlCommand(Control control, Fact canExecute)
        {
            this.control = control;
            this.canExecute = canExecute;
            ctx = AsyncOperationManager.SynchronizationContext;

            if (canExecute != null)
            {
                this.canExecute.PropertyChanged +=
                    (sender, args) =>
                    ctx.Post(x => control.Enabled = canExecute.Value, null);
            }
        }
Beispiel #28
0
 private void LoadingVisible(System.Threading.SynchronizationContext sync, bool val)
 {
     sync.Post(new System.Threading.SendOrPostCallback(delegate {
         this.elementHost1.Visible = val;
         if (val)
         {
             this.elementHost1.BringToFront();
         }
         else
         {
             this.elementHost1.SendToBack();
         }
     }), null);
 }
Beispiel #29
0
 internal static void OnCompletedInternal(Task t, Action continuation, SynchronizationContext capturedContext)
 {
     t.OnCompleted(() =>
     {
         if (capturedContext == null)
         {
             continuation();
         }
         else
         {
             capturedContext.Post(state => ((Action)state)(), continuation);
         }
     });
 }
		private async void MainWindow_Loaded(object sender, RoutedEventArgs e) {
			var deviceName = ConfigurationManager.AppSettings["DeviceName"];
			device = PTZDevice.GetDevice(deviceName, PTZType.Relative);

			url = ConfigurationManager.AppSettings["relayServerUrl"];
			remoteGroup = Environment.MachineName; //They have to hardcode the group, but for us it's our machine name
			connection = new HubConnection(url);
			proxy = connection.CreateHubProxy("RelayHub");

			connection.TraceLevel = TraceLevels.StateChanges | TraceLevels.Events;
			connection.TraceWriter = new PTZRemoteTraceWriter(Log);

			magic = SynchronizationContext.Current;

			proxy.On<int, int>("Move", (x, y) => magic.Post((_) => {
				Log(String.Format("Move({0},{1})", x, y));
				device.Move(x, y);
			}, null));

			proxy.On<int>("Zoom", (z) => magic.Post((_) => {
				Log(String.Format("Zoom({0})", z));
				device.Zoom(z);
			}, null));


			try {
				await connection.Start();
				Log("After connection.Start()");
				await proxy.Invoke("JoinRelay", remoteGroup);
				Log("After JoinRelay");
				Log("Joined remote group - " + remoteGroup);
			}
			catch (Exception pants) {
				Log(pants.GetError().ToString());
				throw;
			}
		}
 private void Do(SynchronizationContext sc, IEnumerable<Tuple<string, Action>> actions, ref int failures)
 {
     foreach (var a in actions)
     {
         try
         {
             a.Item2();
         }
         catch (Exception e)
         {
             failures++;
             var exn = e is TargetInvocationException ? e.InnerException : e;
             var message = a.Item1 + " failed:" + exn.Message;
             sc.Post(state => { testResults.Items.Add(message); }, null);
             return;
         }
     }
 }
Beispiel #32
0
        private async void OnMessage(object sender, MessageEventArgs e)
        {
            Message msg = e.Message;

            if (msg == null || msg.Type != MessageType.Text)
            {
                return;
            }

            _masseges.Id        = e.Message.Chat.Id.ToString();
            _masseges.UserName  = e.Message.Chat.Username;
            _masseges.FirstName = e.Message.Chat.FirstName;
            _masseges.LastName  = e.Message.Chat.LastName;
            _masseges.Date      = DateTime.Now;
            _masseges.Content   = e.Message.Text;
            _masseges.Type      = DisBotMessage.MessageType.OutMessage;
            _synchronizationContext.Post(obj => Log?.Invoke(_masseges), null);
            await _botclient.SendTextMessageAsync(chatId : e.Message.Chat, text : StaticLogicBot.UserInfo.UserLogin);
        }
Beispiel #33
0
        void Instance_LogAdded(bool isError, string log)
        {
            lock (_lockListLogs)
            {
                if (isError)
                {
                    _syn.Post(o =>
                    {
                        if (ListErrorLogsOutput.Count >= MAXLISTERRORLOGSCOUNT)
                        {
                            for (int i = 0; i < 10; i++)
                            {
                                ListErrorLogsOutput.RemoveAt(ListErrorLogsOutput.Count - 1);
                            }
                        }

                        ListErrorLogsOutput.Insert(0, log);
                    }, null);
                }
            }
        }
        public static async Task DownloadHTMLAsync(SynchronizationContext sc, string url, WebBrowser toSet)
        {
            HttpClient client = new HttpClient();
            HttpResponseMessage response = await client.GetAsync(url);
            string content = await response.Content.ReadAsStringAsync();
            sc.Post(rawState =>
            {

                string strToRemove = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">";
                string parsedState = ((string)rawState).Replace(strToRemove, "").Trim();

                HtmlDocument document = new HtmlDocument();
                document.LoadHtml(parsedState);

                HtmlNode collection = document.GetElementbyId("fw-mainColumn");


                toSet.NavigateToString(collection.InnerHtml);

            }, content);
        }    
        internal static void ThrowAsync(Exception exception, SynchronizationContext targetContext)
        {
            if (exception == null)
                return;

            // TODO - decide how to cleanly do it so it lights up if TA is defined
            //if (exception is ThreadAbortException)
            //    return;


            ExceptionDispatchInfo exceptionDispatchInfo = ExceptionDispatchInfo.Capture(exception);

            if (targetContext != null)
            {
                try
                {
                    targetContext.Post((edi) => ((ExceptionDispatchInfo)edi).Throw(), exceptionDispatchInfo);
                }
                catch
                {
                    // Something went wrong in the Post; let's try using the thread pool instead:
                    ThrowAsync(exception, null);
                }
                return;
            }

            bool scheduled = true;
            try
            {
                new SynchronizationContext().Post((edi) => ((ExceptionDispatchInfo)edi).Throw(), exceptionDispatchInfo);
            }
            catch
            {
                // Something went wrong when scheduling the thrower; we do our best by throwing the exception here:
                scheduled = false;
            }

            if (!scheduled)
                exceptionDispatchInfo.Throw();
        }
        async public void makeConnection()
        {
            try
            {
                var hubConnection = new HubConnection("http://bananasvc.azurewebsites.net");
                chat = hubConnection.CreateHubProxy("ChatHub");
                Context = SynchronizationContext.Current;
                chat.On<string, string>("broadcastMessage",
                    (name, message) =>
                        Context.Post(delegate
                        {
                            if (message.Equals("200"))
                                tbstatus.Text = "Elevador Chegou!!!";
                        }, null)
                        );
                await hubConnection.Start();
            }
            catch (Exception ex)
            {

            }
        }
Beispiel #37
0
 protected bool IfReceived(SerialPortManager sp, ProtocolBase protocol, IOBuffer buffer, SynchronizationContext syncContext)
 {
     byte receivedByte;
     if (sp.ReadByte(out receivedByte))
     {
         switch (step)
         {
             case 0:
                 if (receivedByte == protocol.Header)
                 {
                     step++;
                     buffer[counterOfTheReceivedBytes++] = receivedByte;
                 }
                 break;
             case 1:
                 if ((receivedByte & 0x80) == 0x80)
                     RestartReceiv();
                 else
                 {
                     buffer[counterOfTheReceivedBytes++] = receivedByte;
                     if (counterOfTheReceivedBytes == buffer.Size)
                     {
                         if (protocol.UnPack(buffer))
                         {
                             syncContext.Post(delegate
                             {
                                 logger.Log(string.Format("Rx: {0}", buffer.ToString()), Category.Debug, Priority.None);
                             }, null);
                             return true;
                         }
                         else
                             RestartReceiv();
                     }
                 }
                 break;
         }
     }
     return false;
 }
        async private void makeConnection()
        {
            try
            {
                var hubConnection = new HubConnection("http://bananasvc.azurewebsites.net");
                chat = hubConnection.CreateHubProxy("ChatHub");
                Context = SynchronizationContext.Current;
                chat.On<string, string>("broadcastMessage",
                    (name, message) =>
                        Context.Post(delegate
                        {
                            if (message.Equals("100"))
                                CallElevator();
                        }, null)
                        );
                await hubConnection.Start();
                //await chat.Invoke("Notify", chatName.Text, hubConnection.ConnectionId);
            }
            catch (Exception ex)
            {

            }
        }
Beispiel #39
0
        void ListTodayRealTimeTradeRecords_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            StoneStackDailyRecordInfo newItem = null;

            if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Reset)
            {
                _listTodayMinuteTradeRecords.Clear();
                _needRendAll = true;
            }
            if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
            {
                if (e.NewItems == null || e.NewItems.Count == 0)
                {
                    return;
                }
                newItem = e.NewItems[0] as StoneStackDailyRecordInfo;
                if (newItem == null)
                {
                    return;
                }

                //_needRendAll = true;
                if (this._listTodayMinuteTradeRecords.Count == 0)
                {
                    this._listTodayMinuteTradeRecords.Add(newItem);
                }
                else
                {
                    var lastRecord = this._listTodayMinuteTradeRecords[this._listTodayMinuteTradeRecords.Count - 1];

                    if (lastRecord.Day.Hour == newItem.Day.Hour && lastRecord.Day.Minute == newItem.Day.Minute)
                    {
                        this._listTodayMinuteTradeRecords[this._listTodayMinuteTradeRecords.Count - 1] = newItem;
                        this._addItem = false;
                    }
                    else
                    {
                        this._listTodayMinuteTradeRecords.Add(newItem);
                        this._addItem = true;
                    }
                }

                if (this.OpenPrice != newItem.OpenPrice)
                {
                    this._needRendAll = true;
                }
                this.OpenPrice = newItem.OpenPrice;
                double newRangeValue = Math.Abs(Math.Round((double)(newItem.ClosePrice - newItem.OpenPrice), 2));
                if (newRangeValue > this._maxRangeValue)
                {
                    _needRendAll        = true;
                    this._maxRangeValue = newRangeValue;
                }
            }

            _syn.Post(o =>
            {
                if (_needRendAll)
                {
                    Draw();
                }
                else
                {
                    if (newItem != null && newItem.Day != null)
                    {
                        Point newPoint = ConvertStoneStackDailyRecordInfoToPoint(newItem);
                        if (this._addItem)
                        {
                            this.polyLine.Points.Add(newPoint);
                        }
                        else
                        {
                            if (this.polyLine.Points.Count == 0)
                            {
                                this.polyLine.Points.Add(newPoint);
                            }
                            else
                            {
                                this.polyLine.Points[this.polyLine.Points.Count - 1] = newPoint;
                            }
                        }
                    }
                }
            }, null);
        }
Beispiel #40
0
 static public void Thread(System.Threading.SynchronizationContext context, ThreadCallbackType callback)
 {
     context.Post(( object state ) => {
         callback();
     }, null);
 }
 public void Post(SendOrPostCallback sendOrPostCallback, object state)
 {
     synchronizationContext.Post(sendOrPostCallback, state);
 }
Beispiel #42
0
 public void BroadcastToClient(EventDataType eventData)
 {
     syncContext.Post(new System.Threading.SendOrPostCallback(OnBroadcast), eventData);
 }
Beispiel #43
0
 private void ThreadRunForMethodOne(object state)
 {
     m_SyncContext.Post(SendOrPostCallback, state);
 }