System.Windows.Threading.Dispatcher.Invoke(System.Action)

Here are the examples of the csharp api System.Windows.Threading.Dispatcher.Invoke(System.Action) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

807 Examples 7

19 View Source File : BusyCursor.cs
License : MIT License
Project Creator : AntonyCorbett

public void Dispose()
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                Interlocked.Decrement(ref BusyCount);
                StatusChangedEvent?.Invoke(null, EventArgs.Empty);

                if (BusyCount == 0)
                {
                    Mouse.OverrideCursor = null;
                }
            });
        }

19 View Source File : ShowAndFadeAnimations.cs
License : MIT License
Project Creator : avestura

public static Task ShowUsingLinearAnimationAsync(
            this UIElement element,
            int milliSeconds = 500,
            IEasingFunction easingFunction = null)
        {
            return Task.Run(async () =>
            {
                if (element == null) return;
                element.Dispatcher.Invoke(() =>
                {
                    ShowUsingLinearAnimation(element, milliSeconds, easingFunction);
                });
                await Task.Delay(milliSeconds);
            });
        }

19 View Source File : OsTraderMaster.cs
License : Apache License 2.0
Project Creator : AlexWan

private async void TabEnadler()
        {
            try
            {
                if (_tabBotNames != null && !_tabBotNames.Dispatcher.CheckAccess())
                {
                    await Task.Delay(1000);
                    _tabBotNames.Dispatcher.Invoke(TabEnadler);
                    return;
                }

                if (_tabBotNames != null)
                {
                    _tabBotNames.IsEnabled = true;
                }
            }
            catch (Exception error)
            {
                SendNewLogMessage(error.ToString(), LogMessageType.Error);
            }
        }

19 View Source File : WebNavHeaderAdmin.cs
License : MIT License
Project Creator : AntonyCorbett

public void PreviewWebNavHeader()
        {
            AnimateWebNavHeader(
                WebNavHeaderStatus.Showing,
                WebNavHeaderStatus.InPreview,
                0,
                WebHeaderHeight,
                () =>
                {
                    // completed animation
                    Task.Delay(3000).ContinueWith(_ => Application.Current.Dispatcher.Invoke(HideWebNavHeader));
                });
        }

19 View Source File : NotificationObject.cs
License : Apache License 2.0
Project Creator : AlexWan

protected void AddDictionaryElement<T,TF>(T elementName, TF elementValue, IDictionary<T,TF> collection)
        {
            Application.Current.Dispatcher.Invoke(delegate
            {
                collection.Add(elementName, elementValue);
            });
        }

19 View Source File : WpfDispatcherService.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

public void Invoke(Action action)
        {
            Application.Current.Dispatcher.Invoke(action);
        }

19 View Source File : Options.xaml.cs
License : MIT License
Project Creator : Assistant

public void LanguageSelectComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if ((sender as ComboBox).SelectedItem == null)
            {
                // Apply default language
                Console.WriteLine("Applying default language");
                Languages.LoadLanguage("en");
            }
            else
            {
                // Get the matching language from the LoadedLanguages array, then try and use it
                var languageName = (sender as ComboBox).SelectedItem.ToString();
                var selectedLanguage = Languages.LoadedLanguages.Find(language => language.NativeName.CompareTo(languageName) == 0);
                if (Languages.LoadLanguage(selectedLanguage.Name))
                {
                    Properties.Settings.Default.LanguageCode = selectedLanguage.Name;
                    Properties.Settings.Default.Save();
                    if (Languages.FirstRun)
                    {
                        Languages.FirstRun = false;
                    }
                    else
                    {
                        Process.Start(Utils.ExePath, App.Arguments);
                        Application.Current.Dispatcher.Invoke(() => { Application.Current.Shutdown(); });
                    }
                }
            }
        }

19 View Source File : ClientViewModel.cs
License : MIT License
Project Creator : afxw

private void HandleSystemInfo(IPacket packet)
        {
            var systemInfoResponse = (GetSystemInfoResponsePacket)packet;

            var clientInfo = new ClientInfo()
            {
                Identifier = systemInfoResponse.Identifier,
                Address = systemInfoResponse.Address,
                Port = systemInfoResponse.Port,
                Username = systemInfoResponse.Username,
                ComputerName = systemInfoResponse.ComputerName,
                OS = systemInfoResponse.OS
            };

            clientInfo.Owner = server.ConnectedClients.Find(c => clientInfo.Address == c.RemoteAddress.Split(':')[0]);

            Application.Current.Dispatcher.Invoke(() =>
            {
                Clients.Add(clientInfo);
            });
        }

19 View Source File : MarginFadeAnimations.cs
License : MIT License
Project Creator : avestura

public static async Task MarginFadeInAnimationAsync(
            this FrameworkElement element,
            Thickness from,
            Thickness to,
            TimeSpan? duration = null,
            bool useFade = true,
            bool makeVisible = true)
        {
            if (duration == null) duration = new TimeSpan(0, 0, 1);
            await Task.Run(async () =>
            {
                if (element == null) return;
                element.Dispatcher.Invoke(() =>
                {
                    element.MarginFadeInAnimation(from, to, duration, useFade, makeVisible);
                });
                await Task.Delay(duration.Value);
            });

        }

19 View Source File : FileWindowService.cs
License : MIT License
Project Creator : afxw

public void ShowWindow(PaceServer server, ClientInfo client)
        {
            var window = new FileExplorerWindow(server, client);

            // TODO: Probably not an optimal place to put this in, remember to handle this somewhere else
            server.ClientDisconnected += (sender, args) =>
            {
                if (args.Client == client.Owner)
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        window.Close();
                    });
                }
            };

            window.Show();
        }

19 View Source File : TextBoxLineNumbers.cs
License : MIT License
Project Creator : AngryCarrot789

private static void WriteText(TextBox tb, string text)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                tb.SetValue(BindableLineCountProperty, text);
            });
        }

19 View Source File : NotificationObject.cs
License : Apache License 2.0
Project Creator : AlexWan

protected void Clear<T>(IList<T> collection)
        {
            Application.Current.Dispatcher.Invoke(collection.Clear);
        }

19 View Source File : Win7ToastNotificationsProvider.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

private void ShowToast(Win7ToastNotificationViewModel toastContent, string activationCommand)
        {
            bool isActive = false;
            Application.Current.Dispatcher.Invoke(() =>
            {
                isActive = Application.Current.MainWindow?.IsActive ?? false;
            });

            if (isActive)
            {
                // don't show Windows Notifications if the window is focused.
                return;
            }

            void ActivationAction() => ActivationHandler.HandleActivation(
                arguments: activationCommand,
                userInput: new Dictionary<string, object>());

            this.NotificationManager.Show(toastContent, onClick: ActivationAction);
        }

19 View Source File : ImageDisplayManager.cs
License : MIT License
Project Creator : AntonyCorbett

private void ShowImageInControl(string imageFile, Image imageCtrl, ImageFadeType fadeType, double fadeTime, Action completed)
        {
            var shouldFadeIn =
                fadeType == ImageFadeType.FadeIn ||
                fadeType == ImageFadeType.FadeInOut ||
                fadeType == ImageFadeType.CrossFade;

            var imageSrc = _optionsService.CacheImages
                ? ImageCache.GetImage(imageFile)
                : GraphicsUtils.GetBitmapImage(imageFile, ignoreInternalCache: false);

            if (!shouldFadeIn)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    RemoveAnimation(imageCtrl);
                    imageCtrl.Source = imageSrc;
                    completed.Invoke();
                });
            }
            else
            {
                imageCtrl.Opacity = 0.0;
                imageCtrl.Source = imageSrc;

                // This delay allows us to accommodate large images without the apparent loss of fade-in animation
                // the first time an image is loaded. There must be a better way!
                Task.Delay(10).ContinueWith(_ =>
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        var fadeIn = new DoubleAnimation
                        {
                            // note that the fade in time is longer than fade out - just seems to look better
                            Duration = TimeSpan.FromSeconds(fadeTime * 1.2),
                            From = 0.0,
                            To = 1.0,
                        };

                        fadeIn.Completed += (_, _) => completed();
                        imageCtrl.BeginAnimation(UIElement.OpacityProperty, fadeIn);
                    });
                });
            }
        }

19 View Source File : MainWindow.xaml.cs
License : MIT License
Project Creator : ADeltaX

private void UpdateVolume(double volume)
        {

            Dispatcher.Invoke(new Action(() => 
            {
                UpdateVolumeGlyph(volume);
                _isInCodeValueChange = true;
                VolumeSlider.Value = Math.Round(volume);
                _isInCodeValueChange = false;
                textVal.Text = Math.Round(volume).ToString("00");
            }));
        }

19 View Source File : Dispatcher.cs
License : GNU General Public License v3.0
Project Creator : AnyStatus

public void Invoke(Action action)
        {
            if (Application.Current is null)
            {
                Debug.WriteLine("The dispatcher cannot invoke actions because the application is null.");
            }
            else if (Application.Current.Dispatcher is null)
            {
                Debug.WriteLine("The dispatcher cannot invoke actions because the application dispatcher is null.");
            }
            else if (Application.Current.CheckAccess())
            {
                action();
            }
            else
            {
                Application.Current.Dispatcher.Invoke(action);
            }
        }

19 View Source File : MainViewModel.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

private void UpdateDisconnectedComponentsCount(Core.Messaging.DisconnectedRequestMessage update)
        {
            this.DisconnectedComponentCount += update.Disconnected ? 1 : -1;
            this.DisconnectedComponentCount = Math.Max(this.DisconnectedComponentCount, 0); // make sure it never goes negative
            this.TaskManager.UpdateNumberOfBackgroundLoads(this.DisconnectedComponentCount);
            Application.Current.Dispatcher.Invoke(() =>
            {
                this.IsReconnecting = this.DisconnectedComponentCount > 0 || this.TaskManager.RunningTasks.Count > 0;
            });
        }

19 View Source File : MarginFadeAnimations.cs
License : MIT License
Project Creator : avestura

public static async Task MarginFadeOutAnimationAsync(
            this FrameworkElement element,
            Thickness from,
            Thickness to,
            TimeSpan? duration = null,
            bool useFade = true,
            bool makeVisible = true)
        {
            if (duration == null) duration = new TimeSpan(0, 0, 1);
            await Task.Run(async () =>
            {
                if (element == null) return;
                element.Dispatcher.Invoke(() => element.MarginFadeOutAnimation(from, to, duration, useFade, makeVisible));
                await Task.Delay(duration.Value);
            });
        }

19 View Source File : DMSkinComplexWindow.cs
License : MIT License
Project Creator : 944095635

void MainWindow_StateChanged(object sender, EventArgs e)
        {
            //最大化
            if (WindowState == WindowState.Maximized)
            {
                ShadowWindowVisibility(false);
            }
            //默认大小
            if (WindowState == WindowState.Normal)
            {
                if (shadowWindowState)
                {
                    return;
                }
                shadowWindowState = true;
                Task.Factory.StartNew(() =>
                {
                    Thread.Sleep(200);
                    Dispatcher.Invoke(new Action(() =>
                    {
                        //恢复-显示阴影
                        ShadowWindowVisibility(true);
                        shadowWindowState = false;
                        //激活当前窗口
                        Activate();
                        //(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                    }));
                });
            }
            //最小化-隐藏阴影
            if (WindowState == WindowState.Minimized)
            {
                ShadowWindowVisibility(false);
            }
        }

19 View Source File : MarginFadeAnimations.cs
License : MIT License
Project Creator : avestura

public static async Task MarginFadeInAnimationAsync(
            this FrameworkElement element,
            Thickness from,
            Thickness to,
            TimeSpan? duration = null,
            bool useFade = true,
            bool makeVisible = true)
        {
            if (duration == null) duration = new TimeSpan(0, 0, 1);
            await Task.Run(async () =>
            {
                if (element == null) return;
                element.Dispatcher.Invoke(() => element.MarginFadeInAnimation(from, to, duration, useFade, makeVisible));
                await Task.Delay(duration.Value);
            });
        }

19 View Source File : OsTraderMaster.cs
License : Apache License 2.0
Project Creator : AlexWan

public void StartPaint()
        {
            try
            {
                if (!_tabBotNames.Dispatcher.CheckAccess())
                {
                    _tabBotNames.Dispatcher.Invoke(StrategyKeeper_TestingEndEvent);
                    return;
                }

                _tabBotNames.IsEnabled = true;
                if (_fastRegimeOn)
                {
                    _globalController.StartPaint();

                    if (_activPanel != null)
                    {
                        _activPanel.StartPaint(_gridChart, _hostChart, _hostGlreplaced, _hostOpenDeals, _hostCloseDeals, _hostboxLog,
                            _rectangleAroundChart, _hostAlerts, _tabBotTab, _textBoxLimitPrice, _gridChartControlPanel);
                    }

                    _fastRegimeOn = false;
                    ServerMaster.StartPaint();
                    _log.StartPaint(_hostLogPrime);

                }
            }
            catch (Exception error)
            {
                SendNewLogMessage(error.ToString(), LogMessageType.Error);
            }
        }

19 View Source File : NotificationObject.cs
License : Apache License 2.0
Project Creator : AlexWan

protected void AddElement<T>(T element, IList<T> collection)
        {
            Application.Current.Dispatcher.Invoke(delegate
            {
                collection.Insert(0, element);
            });
        }

19 View Source File : DMSkinSimpleWindow.cs
License : MIT License
Project Creator : 944095635

private void WindowRestore()
        {
            Opacity = 0;
            Task.Factory.StartNew(() =>
            {
                Thread.Sleep(50);
                Dispatcher.Invoke(new Action(() =>
                {
                    WindowState = WindowState.Normal;
                    Opacity = 1;
                }));
            });
        }

19 View Source File : NotificationObject.cs
License : Apache License 2.0
Project Creator : AlexWan

protected void RemoveElement<T>(T element, IList<T> collection)
        {
            Application.Current.Dispatcher.Invoke(delegate
            {
                collection.Remove(element);
            });
        }

19 View Source File : GlobalTrigger.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static void OnCtor(NotificationObject config)
        {
            if (WorkContext.IsNoChangedNotify || config == null)
                return;
            Dispatcher.Invoke(() => OnCreate(config));
        }

19 View Source File : AsyncUtility.cs
License : MIT License
Project Creator : AngryCarrot789

public static void RunSync(Action method)
        {
            Application.Current?.Dispatcher?.Invoke(method);
        }

19 View Source File : MainViewModel.cs
License : GNU General Public License v3.0
Project Creator : AndreiFedarets

private void Invoke(Action action)
        {
            _dispatcher.Invoke(action);
        }

19 View Source File : MainWindow.xaml.cs
License : GNU Affero General Public License v3.0
Project Creator : akshinmustafayev

private void ScrollToBottomListBox(ListBox listBox, bool IsAsync)
        {
            if(listBox == null && listBox.Items.Count == 0)
            {
                return;
            }

            if (IsAsync == true)
            {
                this.Dispatcher.Invoke(() =>
                {
                    if (listBox != null)
                    {
                        var border = (Border)VisualTreeHelper.GetChild(listBox, 0);
                        var scrollViewer = (ScrollViewer)VisualTreeHelper.GetChild(border, 0);
                        scrollViewer.ScrollToBottom();
                    }
                });
            }
            else
            {
                if (listBox != null)
                {
                    var border = (Border)VisualTreeHelper.GetChild(listBox, 0);
                    var scrollViewer = (ScrollViewer)VisualTreeHelper.GetChild(border, 0);
                    scrollViewer.ScrollToBottom();
                }
            }
        }

19 View Source File : CreditView.xaml.cs
License : MIT License
Project Creator : anoyetta

private void StartCreadit()
        {
            this.isCreditRunning = true;

            Storyboard.SetTargetName(this.CreaditAnimation, nameof(this.Names));
            Storyboard.SetTargetProperty(this.CreaditAnimation, new PropertyPath(TextBlock.OpacityProperty));
            this.CreaditAnimationStory.Children.Add(this.CreaditAnimation);

            this.showCreditTask = Task.Run(() =>
            {
                foreach (var credit in this.CreditList)
                {
                    if (!this.isCreditRunning)
                    {
                        break;
                    }

                    this.Dispatcher.Invoke(() =>
                    {
                        this.Names.Opacity = 0;

                        this.Subreplacedle.Text = credit.Subreplacedle;
                        this.Names.Text = string.Join(Environment.NewLine, credit.Names);

                        this.Subreplacedle.Visibility = !string.IsNullOrEmpty(credit.Subreplacedle) ?
                            Visibility.Visible :
                            Visibility.Collapsed;

                        this.CreaditAnimationStory.Begin(this, true);
                    });

                    Thread.Sleep(TimeSpan.FromSeconds(7));
                }

                this.Dispatcher.Invoke(() =>
                {
                    this.Close();
                });
            });
        }

19 View Source File : ControlWriter.cs
License : Microsoft Public License
Project Creator : achimismaili

public override void Write(string value)
        {
            if (textbox.Dispatcher.CheckAccess())
            {
                textbox.Text += value;
            }
            else
            {
                textbox.Dispatcher.Invoke(() =>
                {
                    textbox.Text += value;
                });
            }
        }

19 View Source File : ImageDisplayManager.cs
License : MIT License
Project Creator : AntonyCorbett

private static void HideImageInControl(Image imageCtrl, ImageFadeType fadeType, double fadeTime, Action completed)
        {
            var shouldFadeOut = imageCtrl.Source != null &&
                                (fadeType == ImageFadeType.FadeOut ||
                                 fadeType == ImageFadeType.FadeInOut ||
                                 fadeType == ImageFadeType.CrossFade);

            if (!shouldFadeOut)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    completed.Invoke();
                    imageCtrl.Source = null;
                    RemoveAnimation(imageCtrl);
                });
            }
            else
            {
                var fadeOut = new DoubleAnimation
                {
                    Duration = TimeSpan.FromSeconds(fadeTime),
                    From = 1.0,
                    To = 0.0,
                };

                fadeOut.Completed += (_, _) =>
                {
                    completed.Invoke();
                    imageCtrl.Source = null;
                };

                imageCtrl.BeginAnimation(UIElement.OpacityProperty, fadeOut);
            }
        }

19 View Source File : Win10ToastNotificationsProvider.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

private bool ShouldShowToast(string containerId)
        {
            bool isActive = false;
            Application.Current.Dispatcher.Invoke(() =>
            {
                isActive = Application.Current.MainWindow?.IsActive ?? false;

                foreach (var miniChat in this.ChatsViewModel.ActiveMiniChats)
                {
                    if (miniChat.Id == containerId)
                    {
                        isActive = true;
                    }
                }
            });

            return !isActive;
        }

19 View Source File : OperatorViewModel.cs
License : MIT License
Project Creator : AntonyCorbett

private void HandleFileChangesFoundEvent(object? sender, EventArgs e)
        {
            Application.Current.Dispatcher.Invoke(LoadMediaItems);
        }

19 View Source File : DMSkinSimpleWindow.cs
License : MIT License
Project Creator : 944095635

private void StoryboardHide()
        {
            //启动最小化动画
            //StoryboardSlowHide.Begin(this);
            Task.Factory.StartNew(() =>
            {
                Thread.Sleep(300);
                Dispatcher.Invoke(new Action(() =>
                {
                    WindowState = WindowState.Minimized;
                }));
            });
        }

19 View Source File : SnackbarService.cs
License : MIT License
Project Creator : AntonyCorbett

public void Enqueue(object content)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                if (Application.Current.MainWindow?.WindowState != WindowState.Minimized)
                {
                    TheSnackbarMessageQueue.Enqueue(content);
                }
            });
        }

19 View Source File : MainViewModel.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

private void CanShutdownChanged(bool canShutdown)
        {
            if (canShutdown)
            {
                // safe to shutdown now.
                Application.Current.Dispatcher.Invoke(() =>
                {
                    Application.Current.MainWindow.Close();
                });
            }
        }

19 View Source File : MainWindow.xaml.cs
License : GNU General Public License v3.0
Project Creator : arminkz

public void OnFftCalculated(object sender,FftEventArgs e)
        {
            NAudio.Dsp.Complex[] result = e.Result;
            this.Dispatcher.Invoke(new Action(() => {
                Specreplacedyser.Update(result);
                ab.Update(OpenGLControl.OpenGL, result);
            }));
        }

19 View Source File : ClientViewModel.cs
License : MIT License
Project Creator : afxw

private void Server_ClientDisconnected(object sender, ClientEventArgs e)
        {
            var list = new List<ClientInfo>(Clients);
            var client = list.Find(c => c.Owner == e.Client);

            if (client == SelectedClient)
            {
                SelectedClient = null;
            }

            Application.Current.Dispatcher.Invoke(() =>
            {
                Clients.Remove(client);
            });
        }

19 View Source File : Updater.cs
License : MIT License
Project Creator : Assistant

private static void RunNew()
        {
            Process.Start(NewExe, Arguments);
            Application.Current.Dispatcher.Invoke(() => { Application.Current.Shutdown(); });
        }

19 View Source File : MainViewModel.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

private void TaskManager_TaskCountChanged(object sender, EventArgs e)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                this.IsReconnecting = this.DisconnectedComponentCount > 0 || this.TaskManager.RunningTasks.Count > 0;
            });
        }

19 View Source File : ShowAndFadeAnimations.cs
License : MIT License
Project Creator : avestura

public static Task ShowUsingLinearAnimationAsync(
            this UIElement element,
            int milliSeconds = 500,
            IEasingFunction easingFunction = null)
        {
            return Task.Run(async () =>
            {
                if (element == null) return;
                element.Dispatcher.Invoke(() => ShowUsingLinearAnimation(element, milliSeconds, easingFunction));
                await Task.Delay(milliSeconds);
            });
        }

19 View Source File : MainWindow.xaml.cs
License : GNU General Public License v3.0
Project Creator : 44670

public void handleNewGameStr(String gameStr)
        {
            
            this.Dispatcher.Invoke(new Action(() =>
            {
                Console.WriteLine(gameStr);
                gameStrLines = gameStr.Split('\n').Length;
                textBlock.Text = gameStr;
                updateWindowSize();
            }));
        }

19 View Source File : ShowAndFadeAnimations.cs
License : MIT License
Project Creator : avestura

public static Task HideUsingLinearAnimationAsync(
            this UIElement element,
            int milliSeconds = 500,
            IEasingFunction easingFunction = null)
        {
            return Task.Run(async () =>
            {
                if (element == null || !element.IsVisible) return;
                element.Dispatcher.Invoke(() => HideUsingLinearAnimation(element, milliSeconds, easingFunction));
                await Task.Delay(milliSeconds);
            });
        }

19 View Source File : OsTraderMaster.cs
License : Apache License 2.0
Project Creator : AlexWan

public void StopPaint()
        {
            try
            {
                if (!_tabBotNames.Dispatcher.CheckAccess())
                {
                    _tabBotNames.Dispatcher.Invoke(StrategyKeeper_TestingFastEvent);
                    return;
                }
                if (_activPanel != null)
                {
                    _activPanel.StopPaint();
                }

                _fastRegimeOn = true;
                ServerMaster.StopPaint();
                _globalController.StopPaint();
                _tabBotNames.IsEnabled = false;
                _log.StopPaint();

            }
            catch (Exception error)
            {
                SendNewLogMessage(error.ToString(), LogMessageType.Error);
            }
        }

19 View Source File : FileExplorerViewModel.cs
License : MIT License
Project Creator : afxw

private void HandleGetDirectory(IPacket packet)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                Files.Clear();
            });

            var previousDirectory = CurrentDirectory;

            var directoryResponse = (GetDirectoryResponsePacket)packet;

            CurrentDirectory = new FileSystemEntry(directoryResponse.Name, directoryResponse.Path, 0, FileType.Directory);

            if (previousDirectory != null)
            {
                BackHistory.Push(previousDirectory);
            }

            OnPropertyChanged(() => CanGoForward);
            OnPropertyChanged(() => CanGoBackward);

            for (int i = 0; i < directoryResponse.Folders.Length; i++)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    Files.Add(new FileSystemEntry
                    (
                        directoryResponse.Folders[i],
                        System.IO.Path.Combine(CurrentDirectory.Path, directoryResponse.Folders[i]),
                        0,
                        FileType.Directory
                    ));
                });
            }

            for (int i = 0; i < directoryResponse.Files.Length; i++)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    Files.Add(new FileSystemEntry
                    (
                        directoryResponse.Files[i],
                        System.IO.Path.Combine(CurrentDirectory.Path, directoryResponse.Files[i]),
                        directoryResponse.FileSizes[i],
                        FileType.File
                    ));
                });
            }
        }

19 View Source File : SteamBotController.cs
License : GNU General Public License v3.0
Project Creator : 00000vish

static void OnLoggedOn(SteamUser.LoggedOnCallback callback)
        {
            bool isSteamGuard = callback.Result == EResult.AccountLogonDenied;
            bool is2FA = callback.Result == EResult.AccountLoginDeniedNeedTwoFactor;

            if (isSteamGuard || is2FA)
            {
                Console.WriteLine("This account is SteamGuard protected!");

                if (is2FA)
                {
                    Application.Current.Dispatcher.Invoke((Action)delegate
                    {
                        //Console.Write("Please enter your 2 factor auth code from your authenticator app: ");
                        // MainWindow.currentHandle.Show();
                        GetInput GI = new GetInput();
                        twoFactorAuth = GI.Show("Authentication", "Please enter your 2 factor auth code from your authenticator app below", false);
                        GI.Close();
                    });
                }
                else
                {
                    Application.Current.Dispatcher.Invoke((Action)delegate
                    {
                        //Console.Write("Please enter the auth code sent to the email at {0}: ", callback.EmailDomain);
                        //MainWindow.currentHandle.Show();
                        GetInput GI = new GetInput();
                        authCode = GI.Show("Authentication", "Please enter the auth code sent to the email at " + callback.EmailDomain, false);
                        GI.Close();
                    });
                }

                return;
            }

            if (callback.Result != EResult.OK)
            {
                Console.WriteLine("Unable to logon to Steam: {0} / {1}", callback.Result, callback.ExtendedResult);

                isRunning = false;
                return;
            }

            Console.WriteLine("Successfully logged on!");
            loggedIn = true;
            // at this point, we'd be able to perform actions on Steam
        }

19 View Source File : Execute.cs
License : MIT License
Project Creator : 944095635

public static void InitializeWithDispatcher()
        {
            var dispatcher = Dispatcher.CurrentDispatcher;
            executor = (action, async) =>
            {
                //确认是当前的线程
                if (dispatcher.CheckAccess())
                {
                    action();
                }
                else
                {
                    //异步执行
                    if (async)
                    {
                        dispatcher.BeginInvoke(action);
                    }
                    else
                    {
                        dispatcher.Invoke(action);
                    }
                }
            };
        }

19 View Source File : MainWindow.xaml.cs
License : MIT License
Project Creator : ab4d

private void InitializeOvrAndDirectX()
        {
            if (UseOculusRift)
            {
                // Initializing Oculus VR is very simple when using OculusWrapVirtualRealityProvider
                // First we create an instance of OculusWrapVirtualRealityProvider
                _oculusRiftVirtualRealityProvider = new OculusWrapVirtualRealityProvider(_ovr,  multisamplingCount: 4);

                try
                {
                    // Then we initialize Oculus OVR and create a new DXDevice that uses the same adapter (graphic card) as Oculus Rift
                    _dxDevice = _oculusRiftVirtualRealityProvider.InitializeOvrAndDXDevice(requestedOculusSdkMinorVersion: 17);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Failed to initialize the Oculus runtime library.\r\nError: " + ex.Message, "Oculus error", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                string ovrVersionString = _ovr.GetVersionString();
                _originalWindowreplacedle = string.Format("DXEngine OculusWrap Sample (OVR v{0})", ovrVersionString);
                this.replacedle = _originalWindowreplacedle;


                // Reset tracking origin at startup
                _ovr.RecenterTrackingOrigin(_oculusRiftVirtualRealityProvider.SessionPtr);
            }
            else
            {
                // Create DXDevice that will be used to create DXViewportView
                var dxDeviceConfiguration = new DXDeviceConfiguration();
                dxDeviceConfiguration.DriverType = DriverType.Hardware;
                dxDeviceConfiguration.SupportedFeatureLevels = new FeatureLevel[] { FeatureLevel.Level_11_0 }; // Oculus requires at least feature level 11.0

                _dxDevice = new DXDevice(dxDeviceConfiguration);
                _dxDevice.InitializeDevice();

                _originalWindowreplacedle = this.replacedle;
            }



            // Create WPF's Viewport3D
            _viewport3D = new Viewport3D();

            // Create DXViewportView - a control that will enable DirectX 11 rendering of standard WPF 3D content defined in Viewport3D.
            // We use a specified DXDevice that was created by the _oculusRiftVirtualRealityProvider.InitializeOvrAndDXDevice (this way the same adapter is used by Oculus and DXEngine).
            _dxViewportView = new DXViewportView(_dxDevice, _viewport3D);
            
            _dxViewportView.BackgroundColor = Colors.Aqua;

            // Currently DXEngine support showing Oculus mirror texture only with DirectXOverlay presentation type (not with DirectXImage)
            _dxViewportView.PresentationType = DXView.PresentationTypes.DirectXOverlay;

            if (UseOculusRift)
            {
                // The _dxViewportView will show Oculus mirrow window.
                // The mirror window can be any size, for this sample we use 1/2 the HMD resolution.
                _dxViewportView.Width = _oculusRiftVirtualRealityProvider.HmdDescription.Resolution.Width / 2.0;
                _dxViewportView.Height = _oculusRiftVirtualRealityProvider.HmdDescription.Resolution.Height / 2.0;
            }


            // When the DXViewportView is initialized, we set the _oculusRiftVirtualRealityProvider to the DXScene object
            _dxViewportView.DXSceneInitialized += delegate (object sender, EventArgs args)
            {
                if (_dxViewportView.UsedGraphicsProfile.DriverType != GraphicsProfile.DriverTypes.Wpf3D &&
                    _dxViewportView.DXScene != null &&
                    _oculusRiftVirtualRealityProvider != null)
                {
                    // Initialize Virtual reality rendering
                    _dxViewportView.DXScene.InitializeVirtualRealityRendering(_oculusRiftVirtualRealityProvider);


                    // Initialized shadow rendering (see Ab3d.DXEngine.Wpf.Samples project - DXEngine/ShadowRenderingSample for more info
                    _varianceShadowRenderingProvider = new VarianceShadowRenderingProvider()
                    {
                        ShadowMapSize = 1024,
                        ShadowDepthBluringSize = 2,
                        ShadowThreshold = 0.2f
                    };

                    _dxViewportView.DXScene.InitializeShadowRendering(_varianceShadowRenderingProvider);
                }
            };


            // Enable collecting rendering statistics (see _dxViewportView.DXScene.Statistics clreplaced)
            DXDiagnostics.IsCollectingStatistics = true;

            // Subscribe to SceneRendered to collect FPS statistics
            _dxViewportView.SceneRendered += DXViewportViewOnSceneRendered;

            // Add _dxViewportView to the RootGrid
            // Before that we resize the window to be big enough to show the mirrored texture
            this.Width = _dxViewportView.Width + 30;
            this.Height = _dxViewportView.Height + 50;

            RootGrid.Children.Add(_dxViewportView);


            // Create FirstPersonCamera
            _camera = new FirstPersonCamera()
            {
                TargetViewport3D = _viewport3D,
                Position = new Point3D(0, 1, 4),
                Heading = 0,
                Atreplacedude = 0,
                ShowCameraLight = ShowCameraLightType.Never
            };

            RootGrid.Children.Add(_camera);


            // Initialize XBOX controller that will control the FirstPersonCamera
            _xInputCameraController = new XInputCameraController()
            {
                TargetCamera = _camera,
                RotationSpeed = 120,                          // rotation: 120 degrees per second
                MovementSpeed = 2,                            // movement: 2 meters per second
                RotateOnlyHorizontally = true,                // do not rotate up and down (changing atreplacedude) with controller - this is done only HMD
                MoveVerticallyWithDPadButtons = true,
            };

            _xInputCameraController.StartCheckingController();


            // Now we can create our sample 3D scene
            CreateSceneObjects();

            // Add lights
            var lightsVisual3D = new ModelVisual3D();
            var lightsGroup = new Model3DGroup();

            var directionalLight = new DirectionalLight(Colors.White, new Vector3D(0.5, -0.3, -0.3));
            directionalLight.SetDXAttribute(DXAttributeType.IsCastingShadow, true); // Set this light to cast shadow
            lightsGroup.Children.Add(directionalLight);

            var ambientLight = new AmbientLight(System.Windows.Media.Color.FromRgb(30, 30, 30));
            lightsGroup.Children.Add(ambientLight);

            lightsVisual3D.Content = lightsGroup;
            _viewport3D.Children.Add(lightsVisual3D);


            // Start rendering
            if (RenderAt90Fps)
            {
                // WPF do not support rendering at more the 60 FPS.
                // But with a trick where a rendering loop is created in a background thread, it is possible to achieve more than 60 FPS.
                // In case of submitting frames to Oculus Rift at higher FPS, the ovr.SubmitFrame method will limit rendering to 90 FPS.
                // 
                // NOTE:
                // When using DXEngine, it is also possible to render the scene in a background thread. 
                // This requires that the 3D scene is also created in the background thread and that the events and other messages are 
                // preplaceded between UI and background thread in a thread safe way. This is too complicated for this simple sample project.
                // To see one possible implementation of background rendering, see the BackgroundRenderingSample in the Ab3d.DXEngine.Wpf.Samples project.
                var backgroundWorker = new BackgroundWorker();
                backgroundWorker.DoWork += (object sender, DoWorkEventArgs args) =>
                {
                    // Create an action that will be called by Dispatcher
                    var refreshDXEngineAction = new Action(() =>
                    {
                        UpdateScene();

                        // Render DXEngine's 3D scene again
                        if (_dxViewportView != null)
                            _dxViewportView.Refresh();
                    });

                    while (_dxViewportView != null && !_dxViewportView.IsDisposed) // Render until window is closed
                    {
                        if (_oculusRiftVirtualRealityProvider != null && _oculusRiftVirtualRealityProvider.LastSessionStatus.ShouldQuit) // Stop rendering - this will call RunWorkerCompleted where we can quit the application
                            break;

                        // Sleep for 1 ms to allow WPF tasks to complete (for example handling XBOX controller events)
                        System.Threading.Thread.Sleep(1);

                        // Call Refresh to render the DXEngine's scene
                        // This is a synchronous call and will wait until the scene is rendered. 
                        // Because Oculus is limited to 90 fps, the call to ovr.SubmitFrame will limit rendering to 90 FPS.
                        Dispatcher.Invoke(refreshDXEngineAction); 
                    }
                };

                backgroundWorker.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs args)
                {
                    if (_oculusRiftVirtualRealityProvider != null && _oculusRiftVirtualRealityProvider.LastSessionStatus.ShouldQuit)
                        this.Close(); // Exit the application
                };

                backgroundWorker.RunWorkerAsync();
            }
            else
            {
                // Subscribe to WPF rendering event (called approximately 60 times per second)
                CompositionTarget.Rendering += CompositionTargetOnRendering;
            }
        }

19 View Source File : DispatcherSynchronousContext.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public void InvokeInUiThread(Action action)
        {
            if (Dispatcher.CheckAccess())
            {
                action();
            }
            else
            {
                Dispatcher.Invoke(action);
            }
        }

19 View Source File : SmartDispatcher.cs
License : GNU General Public License v3.0
Project Creator : AndreiFedarets

public void Invoke(Action action)
        {
            if (Equals(_dispatcher.Thread, Thread.CurrentThread))
            {
                action();
            }
            else
            {
                _dispatcher.Invoke(action);
            }
        }

See More Examples