示例#1
0
        static void Main()
        {
            var ctx = new DispatcherSynchronizationContext();

            // SynchronizationContext.SetSynchronizationContext(ctx);
            // CallerWithAsync();
            // CallerWithContinuationTask();
            // CallerWithAwaiter();
            // MultipleAsyncMethods();
            // MultipleAsyncMethodsWithCombinators1();
            //   MultipleAsyncMethodsWithCombinators2();
            ConvertingAsyncPattern();
            Console.ReadLine();
        }
示例#2
0
        public void GetWeatherAsync()
        {
            if (requestingContext != null)
            {
                throw new InvalidOperationException("This component can only handle 1 async request at a time");
            }

            requestingContext = (DispatcherSynchronizationContext)DispatcherSynchronizationContext.Current;

            NoArgDelegate fetcher = new NoArgDelegate(this.fetchWeatherFromServer);

            // Launch thread
            fetcher.BeginInvoke(null, null);
        }
示例#3
0
        /// <summary>
        /// Report a mResult to the attached eventhalders (if any) on whether execution succeded or not.
        /// </summary>
        protected void ReportBatchResultEvent(bool bAsnc)
        {
            // non-Asnyc threads are simply blocked until they finish
            // hence completed event is not required to fire
            if (bAsnc == false)
            {
                return;
            }

            SendOrPostCallback callback = ReportTaskCompletedEvent;

            _mRequestingContext.Post(callback, null);
            _mRequestingContext = null;
        }
示例#4
0
        protected override IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state)
        {
            if (Application.Current == null)
            {
                throw new InvalidOperationException("Must have an application");
            }

            DispatcherSynchronizationContext syncContext = new DispatcherSynchronizationContext(Application.Current.Dispatcher);
            object dataContext  = context.DataContext;
            Action showDelegate = () => syncContext.Send(Show, dataContext);

            context.UserState = showDelegate;

            return(showDelegate.BeginInvoke(callback, state));
        }
示例#5
0
        private string fetchWeatherFromServer()
        {
            // do stuff
            string weather = "";

            GetWeatherCompletedEventArgs e =
                new GetWeatherCompletedEventArgs(null, false, null, weather);

            SendOrPostCallback callback = new SendOrPostCallback(DoEvent);

            requestingContext.Post(callback, e);
            requestingContext = null;

            return(e.Weather);
        }
示例#6
0
        public void Run()
        {
            if (DataSetInfos.Count == 0)
            {
                return;
            }

            OnStart();
            foreach (var uploadParam in DataSetInfos)
            {
                uploadParam.Reset();
            }
            _synchronizationContext = new DispatcherSynchronizationContext();
            RunNext();
        }
        public void Post()
        {
            DispatcherSynchronizationContext dsc = new DispatcherSynchronizationContext();
            // that would throw a NRE but we can't catch it
            //dsc.Post (null, this);

            bool complete = false;

            dsc.Post(delegate(object obj) {
                Assert.IsNull(obj, "Post");
                complete = true;
            }, null);

            EnqueueConditional(() => complete);
            EnqueueTestComplete();
        }
示例#8
0
        /// <summary>
        /// Save the threading context of a calling thread to enable event completion handling
        /// in original context when async task has finished (WPF, Winforms and co require this)
        /// </summary>
        /// <param name="bAsnc"></param>
        protected void SaveThreadContext(bool bAsnc)
        {
            // non-Asnyc threads are simply blocked until they finish
            // hence completed event is not required to fire
            if (bAsnc == false)
            {
                return;
            }

            if (mRequestingContext != null)
            {
                throw new InvalidOperationException(ProcessorStrings.STR_CAN_HANDLE_ONLE_1_REQUEST_AT_A_TIME);
            }

            mRequestingContext = (DispatcherSynchronizationContext)SynchronizationContext.Current;
        }
        public void CustomizeView(Accounts model, NodeView nodeView)
        {
            dynamoModel     = nodeView.ViewModel.DynamoViewModel.Model;
            dynamoViewModel = nodeView.ViewModel.DynamoViewModel;
            syncContext     = new DispatcherSynchronizationContext(nodeView.Dispatcher);
            accountsNode    = model;

            var ui = new AccountsUi();

            nodeView.inputGrid.Children.Add(ui);

            //bindings
            ui.DataContext = model;
            ui.Loaded     += Loaded;
            ui.AccountsComboBox.SelectionChanged += SelectionChanged;
        }
示例#10
0
        /// <summary>
        /// Save the threading context of a calling thread to enable event completion handling
        /// in original context when async task has finished (WPF, Winforms and co require this)
        /// </summary>
        /// <param name="bAsnc"></param>
        protected void SaveThreadContext(bool bAsnc)
        {
            // non-Asnyc threads are simply blocked until they finish
            // hence completed event is not required to fire
            if (bAsnc == false)
            {
                return;
            }

            if (_requestingContext != null)
            {
                throw new InvalidOperationException("This component can handle only 1 processing request at a time");
            }

            _requestingContext = (DispatcherSynchronizationContext)SynchronizationContext.Current;
        }
示例#11
0
        void InitGUI()
        {
            SyncContext = new DispatcherSynchronizationContext();
            DeviceManager.DeviceCountChanged += (object o, EventArgs e) => { ShowStatusAsync(string.Format(GreenResources.StatusDevicesConnected, DeviceManager.DeviceCount)); };
            MIStart.DataContext              = DeviceManager;
            MIMode.DataContext               = Settings.KinectMode;
            MIExport.DataContext             = DeviceManager;
            SMC.DataContext                  = Settings;
            IStatus.DataContext              = DeviceManager;
            SBIContinousShooting.DataContext = DeviceManager;

            MainDispatcher           = new DispatcherTimer(DispatcherPriority.Send);
            MainDispatcher.Interval  = new TimeSpan(0, 0, 0, 0, 30);
            MainDispatcher.Tick     += DT_Tick;
            MainDispatcher.IsEnabled = true;
        }
示例#12
0
        public void CustomizeView(CreateStream model, NodeView nodeView)
        {
            dynamoModel     = nodeView.ViewModel.DynamoViewModel.Model;
            dynamoViewModel = nodeView.ViewModel.DynamoViewModel;
            syncContext     = new DispatcherSynchronizationContext(nodeView.Dispatcher);
            accountsNode    = model;

            var ui = new CreateStreamUi();

            nodeView.inputGrid.Children.Add(ui);

            //bindings
            ui.DataContext = model;
            ui.Loaded     += Loaded;
            ui.CreateStreamButton.Click += CreateStreamButtonClick;
        }
示例#13
0
        public StaTaskScheduler()
        {
            using (var threadStartedEvent = new ManualResetEventSlim(initialState: false))
            {
                DispatcherSynchronizationContext synchronizationContext = null;
                StaThread = new Thread(
                    () =>
                {
                    var oldContext = SynchronizationContext.Current;
                    try
                    {
                        // All WPF Tests need a DispatcherSynchronizationContext and we dont want to block pending keyboard
                        // or mouse input from the user. So use background priority which is a single level below user input.
                        synchronizationContext = new DispatcherSynchronizationContext();

                        // xUnit creates its own synchronization context and wraps any existing context so that messages are
                        // still pumped as necessary. So we are safe setting it here, where we are not safe setting it in test.
                        SynchronizationContext.SetSynchronizationContext(
                            synchronizationContext
                            );

                        threadStartedEvent.Set();

                        Dispatcher.Run();
                    }
                    finally
                    {
                        SynchronizationContext.SetSynchronizationContext(oldContext);
                    }
                }
                    );
                StaThread.Name         = $"{nameof(StaTaskScheduler)} thread";
                StaThread.IsBackground = true;
                StaThread.SetApartmentState(ApartmentState.STA);
                StaThread.Start();

                threadStartedEvent.Wait();
                DispatcherSynchronizationContext = synchronizationContext;
            }

            // Work around the WeakEventTable Shutdown race conditions
            AppContext.SetSwitch(
                "Switch.MS.Internal.DoNotInvokeInWeakEventTableShutdownListener",
                isEnabled: true
                );
        }
示例#14
0
        public static bool?Show(
            string message,
            string header,
            MessageBoxButton button = MessageBoxButton.OK,
            MessageBoxImage image   = MessageBoxImage.Asterisk,
            object owner            = null)
        {
            switch (button)
            {
            case MessageBoxButton.OK:
                SystemSounds.Asterisk.Play();
                break;

            case MessageBoxButton.OKCancel:
            case MessageBoxButton.YesNo:
            case MessageBoxButton.YesNoCancel:
                SystemSounds.Exclamation.Play();
                break;
            }

            bool?result = null;
            SendOrPostCallback action = obj => {
                var    depObj      = owner as DependencyObject;
                var    w           = new MessageDialog(message, header, button, image);
                Window windowOwner = depObj == null ? Application.Current.MainWindow : GetWindow(depObj);
                try {
                    w.Owner = windowOwner;
                } catch (InvalidOperationException) { }

                var view = owner as IView;
                if (view != null && view.ImageSource != null)
                {
                    w.Icon = view.ImageSource;
                }
                else if (owner != null && windowOwner != null)
                {
                    w.Icon = windowOwner.Icon;
                }
                w.ShowDialog();
                result = w._result;
            };
            var context = new DispatcherSynchronizationContext(Application.Current.Dispatcher);

            context.Send(action, null);
            return(result);
        }
        public void CustomizeView(ListSelector model, NodeView nodeView)
        {
            DynamoViewmodel            = nodeView.ViewModel.DynamoViewModel;
            SyncContext                = new DispatcherSynchronizationContext(nodeView.Dispatcher);
            ViewModel                  = model;
            ViewModel.EngineController = nodeView.ViewModel.DynamoViewModel.EngineController;
            View = new ListSelectorView
            {
                DataContext = model,
                MaxHeight   = 300,
                MaxWidth    = 200
            };
            nodeView.inputGrid.Children.Add(View);

            model.UpdateItemsCollection += UpdateCollection;
            UpdateCollection();
        }
示例#16
0
        public virtual void CustomizeView(T model, NodeView nodeView)
        {
            this.viewModel   = nodeView.ViewModel.DynamoViewModel;
            this.nodeView    = nodeView;
            this.syncContext = new DispatcherSynchronizationContext(nodeView.Dispatcher);

            NodeModel = model;

            NodeModel.PropertyChanged += (s, e) =>
            {
                if (e.PropertyName == "CachedValue")
                {
                    OnCachedValueChange(s);
                }
                ;
            };
        }
示例#17
0
        private static void VerifySynchronizationContext()
        {
            if (SynchronizationContext.Current != null)
            {
                return;
            }

            if (IsRunningInTest())
            {
                SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
                return;
            }

            var context = new DispatcherSynchronizationContext(Application.Current.Dispatcher);

            SynchronizationContext.SetSynchronizationContext(context);
        }
示例#18
0
        public void CustomizeView(BuiltInParamSelector model, NodeView nodeView)
        {
            if (nodeView?.Dispatcher == null)
            {
                return;
            }

            _dynamoViewmodel            = nodeView.ViewModel.DynamoViewModel;
            _syncContext                = new DispatcherSynchronizationContext(nodeView.Dispatcher);
            _viewModel                  = model;
            _viewModel.EngineController = nodeView.ViewModel.DynamoViewModel.EngineController;
            _view = new BuiltInParamSelectorView();
            nodeView.inputGrid.Children.Add(_view);
            _view.DataContext = model;
            model.RequestChangeBuiltInParamSelector += UpdateParameterSelector;
            UpdateParameterSelector();
        }
示例#19
0
        public void GoBack()
        {
            if (!Deployment.Current.CheckAccess())
            {
                var context = new DispatcherSynchronizationContext(Deployment.Current.Dispatcher);
                context.Send(_ => GoBack(), null);
                return;
            }

            PhoneApplicationFrame root = Application.Current.RootVisual as PhoneApplicationFrame;

            Debug.Assert(root != null, "Root is null");
            if (root.CanGoBack)
            {
                root.GoBack();
            }
        }
    public Dispatcher Build()
    {
        Dispatcher dispatcher       = null;
        var        manualResetEvent = new ManualResetEvent(false);
        var        thread           = new Thread(() =>
        {
            dispatcher = Dispatcher.CurrentDispatcher;
            var synchronizationContext = new DispatcherSynchronizationContext(dispatcher);
            SynchronizationContext.SetSynchronizationContext(synchronizationContext);
            manualResetEvent.Set();
            Dispatcher.Run();
        });

        thread.Start();
        manualResetEvent.WaitOne();
        manualResetEvent.Dispose();
        return(dispatcher);
    }
示例#21
0
        public static bool Show(Exception exception, object owner = null)
        {
            var depObj = owner as DependencyObject;
            var result = false;
            SendOrPostCallback action =
                obj => {
                var w = new ExceptionDialog((Exception)obj);
                try {
                    w.Owner = depObj == null ? Application.Current.MainWindow : GetWindow(depObj);
                } catch (InvalidOperationException) { }

                result = w.ShowDialog() == true;
            };
            var context = new DispatcherSynchronizationContext(Application.Current.Dispatcher);

            context.Send(action, exception);
            return(result);
        }
示例#22
0
        public void CustomizeView(View model, NodeView nodeView)
        {
            dynamoModel     = nodeView.ViewModel.DynamoViewModel.Model;
            dynamoViewModel = nodeView.ViewModel.DynamoViewModel;
            syncContext     = new DispatcherSynchronizationContext(nodeView.Dispatcher);
            viewNode        = model;

            viewNode.OnRequestUpdates += UpdateNode;

            var ui = new ViewUi();

            nodeView.inputGrid.Children.Add(ui);

            //bindings
            ui.DataContext = model;
            //ui.Loaded += model.AddedToDocument;
            ui.ViewStreamButton.Click += ViewStreamButtonClick;
        }
        public void CustomizeView(Send model, NodeView nodeView)
        {
            dynamoModel     = nodeView.ViewModel.DynamoViewModel.Model;
            dynamoViewModel = nodeView.ViewModel.DynamoViewModel;
            syncContext     = new DispatcherSynchronizationContext(nodeView.Dispatcher);
            sendNode        = model;

            sendNode.OnInputsChanged += InputsChanged;

            var ui = new SendUi();

            nodeView.inputGrid.Children.Add(ui);

            //bindings
            ui.DataContext = model;
            //ui.Loaded += model.AddedToDocument;
            ui.SendStreamButton.Click       += SendStreamButtonClick;
            ui.CancelSendStreamButton.Click += CancelSendStreamButtonClick;
        }
示例#24
0
        protected override Task <decimal> InvokeTestMethodAsync(ExceptionAggregator aggregator)
        {
            SharedData.ExecutingTest(TestMethod);
            var sta  = StaTaskScheduler.DefaultSta;
            var task = Task.Factory.StartNew(async() =>
            {
                Debug.Assert(sta.StaThread == Thread.CurrentThread);

                using (await SharedData.TestSerializationGate.DisposableWaitAsync(CancellationToken.None))
                {
                    try
                    {
                        // All WPF Tests need a DispatcherSynchronizationContext and we dont want to block pending keyboard
                        // or mouse input from the user. So use background priority which is a single level below user input.
                        var context = new DispatcherSynchronizationContext();

                        // xUnit creates its own synchronization context and wraps any existing context so that messages are
                        // still pumped as necessary. So we are safe setting it here, where we are not safe setting it in test.
                        SynchronizationContext.SetSynchronizationContext(context);

                        // Just call back into the normal xUnit dispatch process now that we are on an STA Thread with no synchronization context.
                        var invoker  = new WpfTestInvoker(SharedData, Test, MessageBus, TestClass, ConstructorArguments, TestMethod, TestMethodArguments, BeforeAfterAttributes, aggregator, CancellationTokenSource);
                        var baseTask = invoker.RunAsync();
                        do
                        {
                            var delay     = Task.Delay(TimeSpan.FromMilliseconds(10), CancellationTokenSource.Token);
                            var completed = await Task.WhenAny(baseTask, delay).ConfigureAwait(false);
                            if (completed == baseTask)
                            {
                                return(await baseTask.ConfigureAwait(false));
                            }
                        }while (true);
                    }
                    finally
                    {
                        // Cleanup the synchronization context even if the test is failing exceptionally
                        SynchronizationContext.SetSynchronizationContext(null);
                    }
                }
            }, CancellationTokenSource.Token, TaskCreationOptions.None, sta);

            return(task.Unwrap());
        }
        public void Send()
        {
            DispatcherSynchronizationContext dsc = new DispatcherSynchronizationContext();

            // SL throw an NRE while moonlight does not
#if false
            Assert.Throws <NullReferenceException> (delegate {
                dsc.Send(null, this);
            }, "Send(null,object)");
#endif
            bool complete = false;
            dsc.Send(delegate(object obj) {
                Assert.IsNull(obj, "Send");
                complete = true;
            }, null);

            EnqueueConditional(() => complete);
            EnqueueTestComplete();
        }
        public ByteArrayVisualizerControl(IVisualizerObjectProvider objectProvider) : this()
        {
            _objectProvider = objectProvider;

            var prevCtx = SynchronizationContext.Current;

            var syncCtx = new DispatcherSynchronizationContext();

            SynchronizationContext.SetSynchronizationContext(syncCtx);

            try
            {
                FillText();
            }
            finally
            {
                SynchronizationContext.SetSynchronizationContext(prevCtx);
            }
        }
示例#27
0
        public void WindowsRun(Dispatcher dispatcher)
        {
            System.Windows.Interop.MSG msg            = new System.Windows.Interop.MSG();
            SynchronizationContext     oldSyncContext = null;
            SynchronizationContext     newSyncContext = null;

            oldSyncContext = SynchronizationContext.Current;
            newSyncContext = new DispatcherSynchronizationContext(dispatcher);
            SynchronizationContext.SetSynchronizationContext(newSyncContext);
            while (true)
            {
                if (PeekMessage(ref msg, new HandleRef(this, IntPtr.Zero), (WindowMessage)0, (WindowMessage)0, 1))
                {
                    if (msg.message == (int)WindowMessage.WM_QUIT)
                    {
                        break;
                    }
                    bool handled = System.Windows.Interop.ComponentDispatcher.RaiseThreadMessage(ref msg);
                    if (GameWindowHwnd != IntPtr.Zero && msg.hwnd == GameWindowHwnd)
                    {
                        System.Windows.Forms.Application.DoEvents();
                    }
                    if (handled == false)
                    {
                        TranslateMessage(ref msg);
                        DispatchMessage(ref msg);
                    }
                }
                else
                {
                    unsafe
                    {
                        fixed(byte *p = &KeyBoardStats[0])
                        {
                            GetKeyboardState(p);
                        }
                    }
                    System.Windows.Interop.ComponentDispatcher.RaiseIdle();
                }
            }

            SynchronizationContext.SetSynchronizationContext(oldSyncContext);
        }
示例#28
0
        public void CustomizeView(CreateStream model, NodeView nodeView)
        {
            _nodeView       = nodeView;
            dynamoModel     = nodeView.ViewModel.DynamoViewModel.Model;
            dynamoViewModel = nodeView.ViewModel.DynamoViewModel;
            syncContext     = new DispatcherSynchronizationContext(nodeView.Dispatcher);
            createNode      = model;

            var ui = new CreateStreamUi();

            nodeView.inputGrid.Children.Add(ui);

            //bindings
            ui.DataContext = model;
            ui.Loaded     += Loaded;
            ui.CreateStreamButton.Click        += CreateStreamButtonClick;
            ui.AccountsComboBox.DropDownOpened += AccountsComboBoxOnDropDownOpened;

            nodeView.grid.ContextMenu.Items.Add(new Separator());
        }
示例#29
0
        public void CustomizeView(ColorRange model, NodeView nodeView)
        {
            dynamoModel     = nodeView.ViewModel.DynamoViewModel.Model;
            dynamoViewModel = nodeView.ViewModel.DynamoViewModel;
            syncContext     = new DispatcherSynchronizationContext(nodeView.Dispatcher);
            colorRangeNode  = model;

            gradientImage = new Image
            {
                Stretch = Stretch.Fill,
                Width   = 200,
                Height  = Configurations.PortHeightInPixels * 3
            };

            nodeView.inputGrid.Children.Add(gradientImage);

            colorRangeNode.RequestChangeColorRange += UpdateColorRange;

            UpdateColorRange();
        }
示例#30
0
        //public static async Task Main()
        public static Int32 Main(String[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            // https://stackoverflow.com/questions/50901586/how-do-i-resume-on-the-entry-thread-in-an-async-main?noredirect=1#comment88808169_50901586

            #region Attempts at running async code before WPF:
                        #if NEVER
            //AsyncContext.Run( XmlDocumentConfigurationService.Instance.LoadConfigAsync );

            //System.Threading.SynchronizationContext.SetSynchronizationContext(  )

            Int32 th0 = Thread.CurrentThread.ManagedThreadId;
            SynchronizationContext th0Context = SynchronizationContext.Current;

            Dispatcher dispatcher = Dispatcher.CurrentDispatcher;
            DispatcherSynchronizationContext context = new DispatcherSynchronizationContext(dispatcher);
            SynchronizationContext.SetSynchronizationContext(context);

            SynchronizationContext th1Context = SynchronizationContext.Current;

            await XmlDocumentConfigurationService.Instance.LoadConfigAsync();

            Int32 th2 = Thread.CurrentThread.ManagedThreadId;
            SynchronizationContext th2Context = SynchronizationContext.Current;
                        #endif
            #endregion

            XmlDocumentConfigurationService.Instance.LoadConfig();

            ////////////////////

            RegisterDependencies(SimpleIoc.Default);

            ////////////////////

            // Then call into WPF's PresentationBuildTasks-generated Main:
            TeslaTagsApplication.Main();

            return(0);
        }