Exemple #1
0
        public Task PropertyChangeBindingsOccurThroughMainThread() => DispatcherTest.Run(async() =>
        {
            var isOnBackgroundThread        = false;
            var invokeOnMainThreadWasCalled = false;

            DispatcherProviderStubOptions.InvokeOnMainThread = action =>
            {
                invokeOnMainThreadWasCalled = true;
                action();
            };
            DispatcherProviderStubOptions.IsInvokeRequired =
                () => isOnBackgroundThread;

            var vm = new MockViewModel {
                Text = "text"
            };

            var bindable            = new MockBindable();
            var binding             = CreateBinding();
            bindable.BindingContext = vm;
            bindable.SetBinding(MockBindable.TextProperty, binding);

            Assert.False(invokeOnMainThreadWasCalled);

            isOnBackgroundThread = true;

            vm.Text = "updated";

            Assert.True(invokeOnMainThreadWasCalled);
        });
Exemple #2
0
        public Task CreateTimerRepeatingRepeats() =>
        DispatcherTest.Run(async() =>
        {
            var dispatcher = Dispatcher.GetForCurrentThread();

            var ticks = 0;

            var timer = dispatcher.CreateTimer();

            Assert.False(timer.IsRunning);

            timer.Interval    = TimeSpan.FromMilliseconds(200);
            timer.IsRepeating = true;

            timer.Tick += (_, _) =>
            {
                ticks++;
            };

            timer.Start();

            Assert.True(timer.IsRunning);

            // Give it time to repeat at least once
            await Task.Delay(TimeSpan.FromSeconds(1));

            // If it's repeating, ticks will be greater than 1
            Assert.True(ticks > 1);
        });
        public Task MoveOffUIThread() => DispatcherTest.Run(async() =>
        {
            var _dispatcher = Dispatcher.GetForCurrentThread();

            int itemFromThreadPool = -1;

            var source = new ObservableCollection <int> {
                1, 2
            };

            var moc = new MarshalingObservableCollection(source);

            // Replace a value from a threadpool thread
            await Task.Run(() =>
            {
                source.Move(1, 0);
                itemFromThreadPool = (int)moc[0];
            });

            // Check the result on the main thread
            var onMainThreadValue = await _dispatcher.DispatchAsync(() => moc[0]);

            Assert.That(itemFromThreadPool, Is.EqualTo(1), "Should have value from before move");
            Assert.That(onMainThreadValue, Is.EqualTo(2), "Should have value from after move");
        });
        public Task AddOffUIThread() => DispatcherTest.Run(async() =>
        {
            var _dispatcher = Dispatcher.GetForCurrentThread();

            int insertCount         = 0;
            var countFromThreadPool = -1;

            var source = new ObservableCollection <int>();
            var moc    = new MarshalingObservableCollection(source);

            moc.CollectionChanged += (sender, args) =>
            {
                if (args.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
                {
                    insertCount += 1;
                }
            };

            // Add an item from a threadpool thread
            await Task.Run(() =>
            {
                source.Add(1);
                countFromThreadPool = moc.Count;
            });

            // Check the result on the main thread
            var onMainThreadCount = await _dispatcher.DispatchAsync <int>(() =>
            {
                return(moc.Count);
            });

            Assert.That(countFromThreadPool, Is.EqualTo(0), "Count should be zero because the update on the UI thread hasn't run yet");
            Assert.That(onMainThreadCount, Is.EqualTo(1), "Count should be 1 because the UI thread has updated");
            Assert.That(insertCount, Is.EqualTo(1), "The CollectionChanged event should have fired with an Add exactly 1 time");
        });
Exemple #5
0
        public Task CreateTimerNonRepeatingDoesNotRepeat() =>
        DispatcherTest.Run(async() =>
        {
            var dispatcher = Dispatcher.GetForCurrentThread();

            var ticks = 0;

            var timer = dispatcher.CreateTimer();

            Assert.False(timer.IsRunning);

            timer.Interval    = TimeSpan.FromMilliseconds(200);
            timer.IsRepeating = false;

            timer.Tick += (_, _) =>
            {
                ticks++;
            };

            timer.Start();

            Assert.True(timer.IsRunning);

            await Task.Delay(TimeSpan.FromSeconds(1.1));

            Assert.Equal(1, ticks);
        });
        public Task ClearOnUIThread() => DispatcherTest.Run(async() =>
        {
            var _dispatcher = Dispatcher.GetForCurrentThread();

            var countFromThreadPool = -1;

            var source = new ObservableCollection <int>
            {
                1,
                2
            };

            var moc = new MarshalingObservableCollection(source);

            // Call Clear from a threadpool thread
            await Task.Run(() =>
            {
                source.Clear();
                countFromThreadPool = moc.Count;
            });

            // Check the result on the main thread
            var onMainThreadCount = await _dispatcher.DispatchAsync <int>(() => moc.Count);

            Assert.That(countFromThreadPool, Is.EqualTo(2), "Count should be pre-clear");
            Assert.That(onMainThreadCount, Is.EqualTo(0), "Count should be zero because the Clear has been processed");
        });
Exemple #7
0
        public Task SameDispatcherForSameThread() =>
        DispatcherTest.Run(() =>
        {
            var dispatcher1 = Dispatcher.GetForCurrentThread();
            var dispatcher2 = Dispatcher.GetForCurrentThread();

            Assert.Same(dispatcher1, dispatcher2);
        });
Exemple #8
0
        public Task TestImplementationHasDispatcher() => DispatcherTest.Run(() =>
        {
            Assert.False(DispatcherProviderStubOptions.SkipDispatcherCreation);
            Assert.False(Device.IsInvokeRequired);

            // can create things
            var button = new Button();
        });
Exemple #9
0
        public Task BackgroundThreadDoesNotHaveDispatcher() => DispatcherTest.Run(() =>
        {
            // act like the real world
            DispatcherProviderStubOptions.SkipDispatcherCreation = true;

            // can create things
            var button = new Button();
        });
Exemple #10
0
        public Task CreateTimerIsNotNull() =>
        DispatcherTest.Run(() =>
        {
            var dispatcher = Dispatcher.GetForCurrentThread();

            var timer = dispatcher.CreateTimer();

            Assert.NotNull(timer);
        });
Exemple #11
0
        public Task BackgroundThreadDoesNotHaveDispatcher() =>
        DispatcherTest.Run(() =>
        {
            // act like the real world
            DispatcherProviderStubOptions.SkipDispatcherCreation = true;

            var dispatcher = Dispatcher.GetForCurrentThread();

            Assert.Null(dispatcher);
        });
Exemple #12
0
        public Task TestImplementationHasDispatcher() =>
        DispatcherTest.Run(() =>
        {
            Assert.False(DispatcherProviderStubOptions.SkipDispatcherCreation);

            var dispatcher = Dispatcher.GetForCurrentThread();

            Assert.NotNull(dispatcher);
            Assert.False(dispatcher.IsDispatchRequired);
        });
Exemple #13
0
        public Task SynchronizedCollectionAdd() => DispatcherTest.Run(() =>
        {
            bool invoked = false;

            DispatcherProviderStubOptions.IsInvokeRequired   = () => true;
            DispatcherProviderStubOptions.InvokeOnMainThread = action =>
            {
                invoked = true;
                action();
            };

            var collection = new ObservableCollection <string> {
                "foo"
            };
            var context = new object();

            var list = new ListProxy(collection);

            Assert.IsFalse(invoked, "An invoke shouldn't be executed just setting up ListProxy");

            bool executed = false;
            BindingBase.EnableCollectionSynchronization(collection, context, (enumerable, o, method, access) =>
            {
                executed = true;
                Assert.AreSame(collection, enumerable);
                Assert.AreSame(context, o);
                Assert.IsNotNull(method);
                Assert.IsFalse(access);

                lock (enumerable)
                    method();
            });

            var mre = new ManualResetEvent(false);

            Task.Factory.StartNew(() =>
            {
                DispatcherProviderStubOptions.IsInvokeRequired   = () => true;
                DispatcherProviderStubOptions.InvokeOnMainThread = action =>
                {
                    invoked = true;
                    action();
                };

                lock (collection)
                    collection.Add("foo");

                mre.Set();
            }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);

            mre.WaitOne(5000);

            Assert.IsTrue(executed, "Callback was not executed");
            Assert.IsTrue(invoked, "Callback was not executed on the UI thread");
        });
Exemple #14
0
        public Task TestBeginInvokeOnMainThread() => DispatcherTest.Run(() =>
        {
            bool calledFromMainThread = false;
            MockPlatformServices(() => calledFromMainThread = true);

            bool invoked = false;
            Device.BeginInvokeOnMainThread(() => invoked = true);

            Assert.True(invoked, "Action not invoked.");
            Assert.True(calledFromMainThread, "Action not invoked from main thread.");
        });
Exemple #15
0
        public Task TestInvokeOnMainThreadWithSyncAction() => DispatcherTest.Run(async() =>
        {
            bool calledFromMainThread = false;
            MockPlatformServices(() => calledFromMainThread = true);

            bool invoked = false;
            await Device.InvokeOnMainThreadAsync(() => { invoked = true; });

            Assert.True(invoked, "Action not invoked.");
            Assert.True(calledFromMainThread, "Action not invoked from main thread.");
        });
        public Task InitialItemCountsMatch() => DispatcherTest.Run(async() =>
        {
            var _dispatcher = Dispatcher.GetForCurrentThread();

            var source = new ObservableCollection <int> {
                1, 2
            };

            var moc = new MarshalingObservableCollection(source);

            Assert.That(source.Count, Is.EqualTo(moc.Count));
        });
Exemple #17
0
        public Task TestInvokeOnMainThreadWithSyncFunc() => DispatcherTest.Run(async() =>
        {
            bool calledFromMainThread = false;
            MockPlatformServices(() => calledFromMainThread = true);

            bool invoked = false;
            var result   = await Device.InvokeOnMainThreadAsync(() => { invoked = true; return(true); });

            Assert.True(invoked, "Action not invoked.");
            Assert.True(calledFromMainThread, "Action not invoked from main thread.");
            Assert.True(result, "Unexpected result.");
        });
Exemple #18
0
        public Task BackgroundThreadDoesNotGetDispatcherFromMainThread() =>
        DispatcherTest.Run(async() =>
        {
            var dispatcher = Dispatcher.GetForCurrentThread();
            Assert.NotNull(dispatcher);

            await Task.Run(() =>
            {
                DispatcherProviderStubOptions.SkipDispatcherCreation = true;

                var dispatcher = Dispatcher.GetForCurrentThread();
                Assert.Null(dispatcher);
            });
        });
Exemple #19
0
        public Task DifferentDispatcherForDifferentThread() =>
        DispatcherTest.Run(async() =>
        {
            var outerId     = Environment.CurrentManagedThreadId;
            var dispatcher1 = Dispatcher.GetForCurrentThread();

            await Task.Run(() =>
            {
                var innerId     = Environment.CurrentManagedThreadId;
                var dispatcher2 = Dispatcher.GetForCurrentThread();

                Assert.NotEqual(outerId, innerId);
                Assert.NotSame(dispatcher1, dispatcher2);
            });
        });
Exemple #20
0
        public Task TestInvokeOnMainThreadWithAsyncFunc() => DispatcherTest.Run(async() =>
        {
            bool calledFromMainThread = false;
            MockPlatformServices(
                () => calledFromMainThread = true,
                invokeOnMainThread: action => Task.Delay(50).ContinueWith(_ => action()));

            bool invoked = false;
            var task     = Device.InvokeOnMainThreadAsync(async() => { invoked = true; return(true); });
            Assert.True(calledFromMainThread, "Action not invoked from main thread.");
            Assert.False(invoked, "Action invoked early.");

            var result = await task;
            Assert.True(invoked, "Action not invoked.");
            Assert.True(result, "Unexpected result.");
        });
Exemple #21
0
        public Task PushingContentPageToNonNavigationPageThrowsException() => DispatcherTest.Run(async() =>
        {
            Shell shell = new TestShell();
            Routing.RegisterRoute("ContentPage", typeof(ContentPage));
            shell.Items.Add(CreateShellItem(shellItemRoute: "NewRoute", shellSectionRoute: "Section", shellContentRoute: "Content"));

            bool invalidOperationThrown = true;
            DispatcherProviderStubOptions.InvokeOnMainThread = (action) =>
            {
                try
                {
                    action();
                }
                catch (InvalidOperationException)
                {
                    invalidOperationThrown = true;
                }
            };

            Assert.IsTrue(invalidOperationThrown);
        });
        public Task IndexerConsistent() => DispatcherTest.Run(async() =>
        {
            var _dispatcher = Dispatcher.GetForCurrentThread();

            int itemFromThreadPool = -1;

            var source = new ObservableCollection <int> {
                1, 2
            };

            var moc = new MarshalingObservableCollection(source);

            // Call Remove from a threadpool thread
            await Task.Run(() =>
            {
                source.Remove(1);
                itemFromThreadPool = (int)moc[1];
            });

            Assert.That(itemFromThreadPool, Is.EqualTo(2), "Should have indexer value from before remove");
        });
Exemple #23
0
        public Task DispatchDelayedIsNotImmediate() =>
        DispatcherTest.Run(async() =>
        {
            var dispatcher = Dispatcher.GetForCurrentThread();

            var tcs = new TaskCompletionSource <DateTime>();

            var now = DateTime.Now;

            var result = dispatcher.DispatchDelayed(TimeSpan.FromMilliseconds(500), () =>
            {
                var later = DateTime.Now;
                tcs.SetResult(later);
            });

            Assert.True(result);

            var later    = await tcs.Task;
            var duration = (later - now).TotalMilliseconds;

            Assert.True(duration > 450);
        });