Exemplo n.º 1
1
        private static void Main(string[] args)
        {
            CancellationTokenSource cts = new CancellationTokenSource();
            Console.CancelKeyPress +=
                (sender, e) =>
                {
                    e.Cancel = true;
                    cts.Cancel();
                };

            // Since Console apps do not have a SyncronizationContext, we're leveraging the built-in support
            // in WPF to pump the messages via the Dispatcher.
            // See the following for additional details:
            //   http://blogs.msdn.com/b/pfxteam/archive/2012/01/21/10259307.aspx
            //   https://github.com/DotNetAnalyzers/StyleCopAnalyzers/pull/1362
            SynchronizationContext previousContext = SynchronizationContext.Current;
            try
            {
                var context = new DispatcherSynchronizationContext();
                SynchronizationContext.SetSynchronizationContext(context);

                DispatcherFrame dispatcherFrame = new DispatcherFrame();
                Task mainTask = MainAsync(args, cts.Token);
                mainTask.ContinueWith(task => dispatcherFrame.Continue = false);

                Dispatcher.PushFrame(dispatcherFrame);
                mainTask.GetAwaiter().GetResult();
            }
            finally
            {
                SynchronizationContext.SetSynchronizationContext(previousContext);
            }
        }
    void EnsureInitialized()
    {
        if (_dispatcher != null && _context != null)
        {
            return;
        }

        lock (initializationLock)
        {
            if (_dispatcher != null && _context != null)
            {
                return;
            }

            try
            {
                _dispatcher = Deployment.Current.Dispatcher;
                _context = new DispatcherSynchronizationContext(_dispatcher);
            }
            catch (InvalidOperationException)
            {
                throw new Exception("Initialised called from non-UI thread."); 
            }
        }
    }
        private void EnsureInitialized()
        {
            if (dispatcher != null && context != null)
            {
                return;
            }

            lock (initializationLock)
            {
                if (dispatcher != null && context != null)
                {
                    return;
                }

                try
                {
#if SILVERLIGHT
                dispatcher = System.Windows.Deployment.Current.Dispatcher;
#else
                    dispatcher = Dispatcher.CurrentDispatcher;
#endif
                    context = new DispatcherSynchronizationContext(dispatcher);
                }
                catch (InvalidOperationException)
                {
                    throw new Exception("Initialised called from non-UI thread.");
                }
            }
        }
Exemplo n.º 4
0
        private static void Main(string[] args)
        {
            CancellationTokenSource cts = new CancellationTokenSource();
            Console.CancelKeyPress +=
                (sender, e) =>
                {
                    e.Cancel = true;
                    cts.Cancel();
                };

            SynchronizationContext previousContext = SynchronizationContext.Current;
            try
            {
                var context = new DispatcherSynchronizationContext();
                SynchronizationContext.SetSynchronizationContext(context);

                DispatcherFrame dispatcherFrame = new DispatcherFrame();
                Task mainTask = MainAsync(args, cts.Token);
                mainTask.ContinueWith(task => dispatcherFrame.Continue = false);

                Dispatcher.PushFrame(dispatcherFrame);
                mainTask.GetAwaiter().GetResult();
            }
            finally
            {
                SynchronizationContext.SetSynchronizationContext(previousContext);
            }
        }
Exemplo n.º 5
0
        public override Task<RunSummary> RunAsync(IMessageSink diagnosticMessageSink, IMessageBus messageBus, object[] constructorArguments, ExceptionAggregator aggregator, CancellationTokenSource cancellationTokenSource)
        {
            var sta = StaTaskScheduler.DefaultSta;
            var task = Task.Factory.StartNew(async () =>
            {
                Debug.Assert(sta.Threads.Length == 1);
                Debug.Assert(sta.Threads[0] == Thread.CurrentThread);

                using (await _wpfTestSerializationGate.DisposableWaitAsync())
                {
                    try
                    {
                        // Sync up FTAO to the context that we are creating here. 
                        ForegroundThreadAffinitizedObject.CurrentForegroundThreadData = new ForegroundThreadData(
                            Thread.CurrentThread,
                            StaTaskScheduler.DefaultSta,
                            ForegroundThreadDataKind.StaUnitTest);

                        // 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 dispatcherSynchronizationContext = 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(dispatcherSynchronizationContext);

                        // Just call back into the normal xUnit dispatch process now that we are on an STA Thread with no synchronization context.
                        var baseTask = base.RunAsync(diagnosticMessageSink, messageBus, constructorArguments, aggregator, cancellationTokenSource);
                        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);
                            }

                            // Schedule a task to pump messages on the UI thread.  
                            await Task.Factory.StartNew(
                                () => WaitHelper.WaitForDispatchedOperationsToComplete(DispatcherPriority.ApplicationIdle),
                                cancellationTokenSource.Token,
                                TaskCreationOptions.None,
                                sta).ConfigureAwait(false);
                        }
                        while (true);
                    }
                    finally
                    {
                        ForegroundThreadAffinitizedObject.CurrentForegroundThreadData = null;

                        // Cleanup the synchronization context even if the test is failing exceptionally
                        SynchronizationContext.SetSynchronizationContext(null);
                    }
                }
            }, cancellationTokenSource.Token, TaskCreationOptions.None, sta);

            return task.Unwrap();
        }
        object RunOnUIThread(DispatcherOperationCallback dispatcherMethod, bool async)
        {
            if (Application.Current != null)
            {
                if (Application.Current.Dispatcher.Thread == Thread.CurrentThread)
                {
                    // This avoids dispatching to the UI thread if we are already in the UI thread.
                    // Without this runing a command like 1/0 was throwing due to nested dispatches.
                    return dispatcherMethod.Invoke(null);
                }
            }

            Exception e = null;
            object returnValue = null;
            SynchronizationContext sync = new DispatcherSynchronizationContext(Dispatcher);
            if (sync == null) { return null; }
            if (async)
            {
                sync.Post(
                    new SendOrPostCallback(delegate(object obj)
                    {
                        try
                        {
                            returnValue = dispatcherMethod.Invoke(obj);
                        }
                        catch (Exception uiException)
                        {
                            e = uiException;
                        }
                    }),
                    null);

            }
            else
            {
                sync.Send(
                    new SendOrPostCallback(delegate(object obj)
                    {
                        try
                        {
                            returnValue = dispatcherMethod.Invoke(obj);
                        }
                        catch (Exception uiException)
                        {
                            e = uiException;
                        }
                    }),
                    null);

            }

            if (e != null)
            {
                throw new System.Reflection.TargetInvocationException(e.Message, e);
            }
            return returnValue;
        }
		public void UserSuppliedDispatcher ()
		{
			Assert.Throws<ArgumentNullException> (delegate {
				new DispatcherSynchronizationContext (null);
			}, ".ctor(null)");

			Dispatcher d = Application.Current.RootVisual.Dispatcher;
			DispatcherSynchronizationContext dsc = new DispatcherSynchronizationContext (d);
			Assert.AreNotSame (dsc, dsc.CreateCopy (), "CreateCopy");
		}
    public void Initialize(Dispatcher dispatcher)
    {
        if (dispatcher == null)
            throw new ArgumentNullException("dispatcher");

        lock (initializationLock)
        {
            this._dispatcher = dispatcher;
            _context = new DispatcherSynchronizationContext(dispatcher);
        }
    }
Exemplo n.º 9
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);
        }
		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 ();
		}
Exemplo n.º 11
0
    static void Main()
    {
      var ctx = new DispatcherSynchronizationContext();

      // SynchronizationContext.SetSynchronizationContext(ctx);
      // CallerWithAsync();
      // CallerWithContinuationTask();
      // CallerWithAwaiter();
      // MultipleAsyncMethods();
      // MultipleAsyncMethodsWithCombinators1();
      //   MultipleAsyncMethodsWithCombinators2();
      ConvertingAsyncPattern();
      Console.ReadLine();


    }
Exemplo n.º 12
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);
		}
        static void Main(string[] args)
        {
#if NET46
            var ctx = new DispatcherSynchronizationContext();

            SynchronizationContext.SetSynchronizationContext(ctx);
#endif
            if (args.Length != 1)
            {
                Usage();
                return;
            }

            switch (args[0].ToLower())
            {
                case "-async":
                    CallerWithAsync();
                    break;
                case "-cont":
                    CallerWithContinuationTask();
                    break;
                case "-awaiter":
                    CallerWithAwaiter();
                    break;
                case "-masync":
                    MultipleAsyncMethods();
                    break;
                case "-comb":
                    MultipleAsyncMethodsWithCombinators1();
                    break;
                case "-comb2":
                    MultipleAsyncMethodsWithCombinators2();
                    break;
#if NET46
                case "-casync":
                    ConvertingAsyncPattern();
                    break;
#endif
                default:
                    Usage();
                    break;
            }

            ReadLine();
        }
		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 ();
		}
Exemplo n.º 15
0
    public static void RunInWpfSyncContext(Func<Task> function) {
      if (function == null) throw new ArgumentNullException("function");
      var prevCtx = SynchronizationContext.Current;
      try {
        var syncCtx = new DispatcherSynchronizationContext();
        SynchronizationContext.SetSynchronizationContext(syncCtx);

        var task = function();
        if (task == null) throw new InvalidOperationException();

        var frame = new DispatcherFrame();
        var t2 = task.ContinueWith(x => { frame.Continue = false; }, TaskScheduler.Default);
        Dispatcher.PushFrame(frame);   // execute all tasks until frame.Continue == false

        task.GetAwaiter().GetResult(); // rethrow exception when task has failed 
      } finally {
        SynchronizationContext.SetSynchronizationContext(prevCtx);
      }
    }
Exemplo n.º 16
0
        protected override void OnStartup(StartupEventArgs e)
        {
            // run bootstrapper
            Bootstrapper bootstrapper = new Bootstrapper();
            bootstrapper.Run();

            // set shut down mode
            ShutdownMode = ShutdownMode.OnExplicitShutdown;
            MainContext = (DispatcherSynchronizationContext)DispatcherSynchronizationContext.Current;

            MainWindow.Closing += (sender, args) =>
                MainContext.Send(o => Shutdown(), null);

            // handle exceptions
            DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException);
            
            base.OnStartup(e);

            MainWindow.Show();
        }
Exemplo n.º 17
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;
 }
        /// <summary>
        ///     Create a copy of this SynchronizationContext.
        /// </summary>
        public override SynchronizationContext CreateCopy()
        {
            DispatcherSynchronizationContext copy;

            if (BaseCompatibilityPreferences.GetReuseDispatcherSynchronizationContextInstance())
            {
                copy = this;
            }
            else
            {
                if (BaseCompatibilityPreferences.GetFlowDispatcherSynchronizationContextPriority())
                {
                    copy = new DispatcherSynchronizationContext(_dispatcher, _priority);
                }
                else
                {
                    copy = new DispatcherSynchronizationContext(_dispatcher, DispatcherPriority.Normal);
                }
            }

            return(copy);
        }
Exemplo n.º 19
0
        public static void Run(Func<Task> func)
        {
            var prevCtx = SynchronizationContext.Current;
            try
            {
                var syncCtx = new DispatcherSynchronizationContext();
                SynchronizationContext.SetSynchronizationContext(syncCtx);

                var t = func();
                if (t == null) throw new InvalidOperationException();

                var frame = new DispatcherFrame();
                t.ContinueWith(_ => { frame.Continue = false; }, TaskScheduler.Default);
                Dispatcher.PushFrame(frame);

                t.GetAwaiter().GetResult();
            }
            finally
            {
                SynchronizationContext.SetSynchronizationContext(prevCtx);
            }
        }
Exemplo n.º 20
0
        private void InvokeImpl()
        {
            SynchronizationContext oldSynchronizationContext = SynchronizationContext.Current;

            try
            {
                // We are executing under the "foreign" execution context, but the
                // SynchronizationContext must be for the correct dispatcher and
                // priority.
                DispatcherSynchronizationContext newSynchronizationContext;
                if(BaseCompatibilityPreferences.GetReuseDispatcherSynchronizationContextInstance())
                {
                    newSynchronizationContext = Dispatcher._defaultDispatcherSynchronizationContext;
                }
                else
                {
                    if(BaseCompatibilityPreferences.GetFlowDispatcherSynchronizationContextPriority())
                    {
                        newSynchronizationContext = new DispatcherSynchronizationContext(_dispatcher, _priority);
                    }
                    else
                    {
                        newSynchronizationContext = new DispatcherSynchronizationContext(_dispatcher, DispatcherPriority.Normal);
                    }
                }
                SynchronizationContext.SetSynchronizationContext(newSynchronizationContext);


                // Win32 considers timers to be low priority.  Avalon does not, since different timers
                // are associated with different priorities.  So we promote the timers before we
                // invoke any work items.
                _dispatcher.PromoteTimers(Environment.TickCount);
                
                if(_useAsyncSemantics)
                {
                    try
                    {
                        _result = InvokeDelegateCore();
                    }
                    catch(Exception e)
                    {
                        // Remember this for the later call to InvokeCompletions.
                        _exception = e;
                    }
                }
                else
                {
                    // Invoke the delegate and route exceptions through the dispatcher events.
                    _result = _dispatcher.WrappedInvoke(_method, _args, _numArgs, null);

                    // Note: we do not catch exceptions, they flow out the the Dispatcher.UnhandledException handling.
                }
            }
            finally
            {
                SynchronizationContext.SetSynchronizationContext(oldSynchronizationContext);
            }
        }
Exemplo n.º 21
0
 public void SetSyncContext(Dispatcher dispatcher)
 {
     _syncContext = new DispatcherSynchronizationContext(App.Current.RootVisual.Dispatcher);
 }
        /// <summary>
        ///     Create a copy of this SynchronizationContext.
        /// </summary>
        public override SynchronizationContext CreateCopy()
        {
            DispatcherSynchronizationContext copy;
            
            if(BaseCompatibilityPreferences.GetReuseDispatcherSynchronizationContextInstance())
            {
                copy = this;
            }
            else
            {
                if(BaseCompatibilityPreferences.GetFlowDispatcherSynchronizationContextPriority())
                {
                    copy = new DispatcherSynchronizationContext(_dispatcher, _priority);
                }
                else
                {
                    copy = new DispatcherSynchronizationContext(_dispatcher, DispatcherPriority.Normal);
                }
            }

            return copy;
        }
		public void AddControl_DifferentThreadInContextUsingConfiguration_UsesAmbientContext()
		{
			var window = new DummyWindow();
			var client = container.Resolve<ClassUsingWindowInAmbientContext>();
			ExecuteInThread(() =>
			{
				var dispatcherCtx = new DispatcherSynchronizationContext(window.Dispatcher);
				SynchronizationContext.SetSynchronizationContext(dispatcherCtx);
				client.DoWork(window.Panel);
			});
			Assert.IsNull(uncaughtException, "Expected no exception");
		}
Exemplo n.º 24
0
 public void Initialize(Dispatcher dispatcher)
 {
     ArgumentValidator.AssertNotNull(dispatcher, "dispatcher");
     lock (initializationLock)
     {
         this.dispatcher = dispatcher;
         context = new DispatcherSynchronizationContext(dispatcher);
     }
 }
Exemplo n.º 25
0
        private Dispatcher() 
        {
            _queue = new PriorityQueue<DispatcherOperation>(); 
 
            _tlsDispatcher = this; // use TLS for ownership only
            _dispatcherThread = Thread.CurrentThread; 

            // Add ourselves to the map of dispatchers to threads.
            lock(_globalLock)
            { 
                _dispatchers.Add(new WeakReference(this));
            } 
 
            _unhandledExceptionEventArgs = new DispatcherUnhandledExceptionEventArgs(this);
            _exceptionFilterEventArgs = new DispatcherUnhandledExceptionFilterEventArgs(this); 

            _dispatcherSynchronizationContext = new DispatcherSynchronizationContext(this);

            // Create the message-only window we use to receive messages 
            // that tell us to process the queue.
            MessageOnlyHwndWrapper window = new MessageOnlyHwndWrapper(); 
            _window = new SecurityCriticalData<MessageOnlyHwndWrapper>( window ); 

            _hook = new HwndWrapperHook(WndProcHook); 
            _window.Value.AddHook(_hook);
        }
Exemplo n.º 26
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);
                    var 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 Default ()
		{
			DispatcherSynchronizationContext dsc = new DispatcherSynchronizationContext ();
			Assert.AreNotSame (dsc, dsc.CreateCopy (), "CreateCopy");
		}
Exemplo n.º 28
0
 public WpfDispatchService(DispatcherObject app)
 {
     Dispatcher = app.Dispatcher;
     SyncContext = new DispatcherSynchronizationContext(Dispatcher);
 }
Exemplo n.º 29
0
        public MainWindow()
        {
            InitializeComponent();

            SearchResults = new ThreadSafeObservableCollection<SearchResult>(null, 750000);
            DisplaySearchResults = new ThreadSafeObservableCollection<SearchResult>();

            _uiSynchronizationContext = new DispatcherSynchronizationContext(Application.Current.Dispatcher);
            _taskConsumer = Task.Factory.StartNew(() => ConsumeTasks(_tasks));

            _updateFilter = new DeferredAction(FilterResults);

            _journals = new List<UsnJournal>();

            // TODO: Convert to a user setting
            string[] drives = { "C" };

            DataContext = this;

            if (DesignerProperties.GetIsInDesignMode(this))
            {
                return;
            }

            _predicates = new Dictionary<PredicateOption, Func<SearchResult, bool>>
            {
                {
                    PredicateOption.None,
                    result => SearchCaseInsensitive(result.Name)
                },
                {
                    PredicateOption.MultipleTerms,
                    result => SearchCaseInsensitiveMultiple(result.Name)
                },
                {
                    PredicateOption.CaseSensitive,
                    result => Search(result.Name)
                },
                {
                    PredicateOption.CaseSensitive | PredicateOption.MultipleTerms,
                    result => SearchMultiple(result.Name)
                }
            };

            _searchTermNotifier = new PropertyChangeNotifier(this, "SearchTerm");
            _searchTermNotifier.ValueChanged += OnSearchTermChanged;

            AddTask(() => EnumerateJournals(drives), "Enumerating journals");
        }
Exemplo n.º 30
0
        public void Run()
        {
            if (DataSetInfos.Count == 0)
            {
                return;
            }

            OnStart();

            foreach (var uploadParam in DataSetInfos)
            {
                uploadParam.Reset();
            }

            _synchronizationContext = new DispatcherSynchronizationContext();

            RunNext();
        }