internal static void Uninstall(bool turnOffAutoInstall)
 {
     if (AutoInstall)
     {
         WindowsFormsSynchronizationContext winFormsSyncContext = AsyncOperationManager.SynchronizationContext as WindowsFormsSynchronizationContext;
         if (winFormsSyncContext != null)
         {
             try {
                 if (previousSyncContext == null)
                 {
                     AsyncOperationManager.SynchronizationContext = new SynchronizationContext();
                 }
                 else
                 {
                     AsyncOperationManager.SynchronizationContext = previousSyncContext;
                 }
             }
             finally {
                 previousSyncContext = null;
             }
         }
     }
     if (turnOffAutoInstall)
     {
         AutoInstall = false;
     }
 }
 internal static void Uninstall(bool turnOffAutoInstall)
 {
     if (AutoInstall)
     {
         WindowsFormsSynchronizationContext winFormsSyncContext = AsyncOperationManager.SynchronizationContext as WindowsFormsSynchronizationContext;
         if (winFormsSyncContext != null)
         {
             try {
                 new PermissionSet(PermissionState.Unrestricted).Assert();
                 if (previousSyncContext == null)
                 {
                     AsyncOperationManager.SynchronizationContext = new SynchronizationContext();
                 }
                 else
                 {
                     AsyncOperationManager.SynchronizationContext = previousSyncContext;
                 }
             }
             finally {
                 previousSyncContext = null;
                 CodeAccessPermission.RevertAssert();
             }
         }
     }
     if (turnOffAutoInstall)
     {
         AutoInstall = false;
     }
 }
Esempio n. 3
0
        public MapAdapter(GMapControl mapControl)
        {
            _context = new WindowsFormsSynchronizationContext();

            _mapControl = mapControl;

            IObservable<Unit> positionChanged = Observable
                .FromEvent<PositionChanged, PointLatLng>(
                    action => point => action(point),
                    handler => _mapControl.OnPositionChanged += handler,
                    handler => _mapControl.OnPositionChanged -= handler)
                .Select(i => Unit.Default);


            IObservable<Unit> mapZoom = Observable
                .FromEvent<MapZoomChanged, Unit>(
                    action => () => action(Unit.Default),
                    handler => _mapControl.OnMapZoomChanged += handler,
                    handler => _mapControl.OnMapZoomChanged -= handler);


            MapChanged = positionChanged
                .Merge(mapZoom)
                .ObserveOn(ThreadPoolScheduler.Instance);

            mapControl.OnMapDrag += MapControl_OnMapDrag;
            mapControl.OnPolygonClick += Control_OnPolygonClick;
        }
 public BrowserController()
 {
     obj = this;
     sc = new WindowsFormsSynchronizationContext();
     fd = new FolderBrowserDialog();
     startBrowser(Server.getServer().current_page);
 }
Esempio n. 5
0
        public int GetFileFormatIndex(string path, string sFormats)
        {

            if (System.Windows.Application.Current == null)
                new System.Windows.Application { ShutdownMode = System.Windows.ShutdownMode.OnExplicitShutdown };

            var context = /*SynchronizationContext.Current ??*/ new WindowsFormsSynchronizationContext();
            string fileFormatByDefault = "Portable Document Format (*.pdf)";

            try
            {
                WorkshareOnline.Instance.Security.Authenticate(context);

                var fileFormats = ParseFormats(sFormats);
                var window = new FileSaveWindow(path, fileFormats);

                if (fileFormats.Contains(fileFormatByDefault))
                {
                    window.SelectedFileFormatIndex = fileFormats.FindIndex(x => x.Equals(fileFormatByDefault, StringComparison.InvariantCultureIgnoreCase));
                }
                
                new System.Windows.Interop.WindowInteropHelper(window).Owner = Process.GetCurrentProcess().MainWindowHandle;

                if (window.ShowDialog() == true)
                {
                    platformFolder = (IPlatformFolder)window.SelectedEntity;
                    fileName = window.FileName;
                    return window.SelectedFileFormatIndex;
                }
            }
            catch (OperationCanceledException)
            {
                // ignore the user has cancelled
            }
            catch (UnauthorizedAccessException e)
            {
                Workshare.Interop.Messaging.WsMessage.ShowMessage(IntPtr.Zero,
                    e.Message, Workshare.Interop.Messaging.MessageButtons.WsOK,
                    Workshare.Interop.Messaging.MessageBranding.WsDefault,
                    Workshare.Interop.Messaging.MessageType.WsErrorIcon, "",
                    0);
            }
            catch (Exception e)
            {
                var message = e.InnerException == null ? e.Message : e.InnerException.Message;

                Workshare.Interop.Messaging.WsMessage.ShowMessage(IntPtr.Zero,
                    "Error saving to Workshare: \n\n" + message, Workshare.Interop.Messaging.MessageButtons.WsOK,
                    Workshare.Interop.Messaging.MessageBranding.WsDefault,
                    Workshare.Interop.Messaging.MessageType.WsErrorIcon, "",
                    0);
            }

            return -1;
        }
Esempio n. 6
0
        /// <summary>
        /// Constructor of Sandbox control
        /// </summary>
        public Sandbox()
        {
            InitializeComponent();

            _syncContext = AsyncOperationManager.SynchronizationContext as WindowsFormsSynchronizationContext;
            _storage = null;

            listViewFilesSorter = new ListViewColumnSorter();
            lstFiles.ListViewItemSorter = listViewFilesSorter;
            lstFiles.Sort();
        } 
Esempio n. 7
0
 void ISnapInMessagePumpProxy.Run()
 {
     Application.ThreadException += new ThreadExceptionEventHandler(this.OnThreadException);
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     WindowsFormsSynchronizationContext.AutoInstall = false;
     SynchronizationContext syncContext = new WindowsFormsSynchronizationContext();
     SynchronizationContextCache.OriginalContext = syncContext;
     SynchronizationContext.SetSynchronizationContext(syncContext);
     Application.AddMessageFilter(this);
     Application.Run();
 }
Esempio n. 8
0
 private void InitializeAddin()
 {
     MissingType = System.Type.Missing;
     SynchronizationContext windowsFormsSynchronizationContext = new WindowsFormsSynchronizationContext();
     SynchronizationContext.SetSynchronizationContext(windowsFormsSynchronizationContext);
     TaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
     Log.InitLog(@"D:/hookeditem.log");
     Log.Info("*******START Addin*********");
     Log.Info("Main thread VSTA is {0} {1}", Thread.CurrentThread.Name, Thread.CurrentThread.ManagedThreadId);
     HookedItemsCallbacks callbacks = new HookedItemsCallbacks();
     HookedFolderItems = new HookedFolderItems(callbacks);
     HookedFolderItems.Initialize();
 }
Esempio n. 9
0
        public Form2()
        {
            Thread.CurrentThread.Name = "UIThread";

            var syncctx = new WindowsFormsSynchronizationContext();
            var btnRunErrOnMain = new Button();
            btnRunErrOnMain.Text = "Run (Err on Main)";
            btnRunErrOnMain.Click += (sender, args) => {
                FrmDlg dlg = new FrmDlg();
                throw new Exception("Error en el Form. Thread #" + Thread.CurrentThread.Name);
            };

            var btnRun = new Button();
            btnRun.Text = "Run";
            btnRun.Click += (sender, args) => {
                FrmDlg dlg = new FrmDlg();
                dlg.Confirm = (next, exHandler) => {
                    var t  = new Thread(() => {
                        try {
                            int i = 0;
                            while (true) {
                                i++;
                                if (i == 10000000) {
                                    MessageBox.Show("Running on Thread #" + Thread.CurrentThread.Name);
                                    Die("Error interno del script. on thread #" + Thread.CurrentThread.Name);
                                }
                            }
                            MessageBox.Show("Exit loop");
                            syncctx.Post(ui => { next(); }, null);
                        }
                        catch (Exception ex) {
                            syncctx.Post(ui => { exHandler(ex); }, null);
                        }
                    });
                    t.Name = "Foo";
                    t.Start();
                };

                dlg.Cancel = delegate {
                    MessageBox.Show("Cancel");
                };

                dlg.Show();
            };

            Controls.Add(btnRun);
            btnRunErrOnMain.Top = btnRun.Top + 30;
            Controls.Add(btnRunErrOnMain);
        }
Esempio n. 10
0
        public Context()
        {
            MainSynchronizationContext = new WindowsFormsSynchronizationContext();
            Mail.Received += new Mail.ReceivedDelegate(ReceiveCallback);
            ThreadExit += new EventHandler(Context_ThreadExit);
            SystemEvents.SessionSwitch += new SessionSwitchEventHandler(SystemEvents_SessionSwitch);

            UpdateTimer = new System.Timers.Timer(UpdateFrequency * 1000);
            UpdateTimer.Elapsed += new System.Timers.ElapsedEventHandler(UpdateTimer_Tick);

            InstallIcon();

            LoadSettings();

            UpdateState();
        }
Esempio n. 11
0
        public static void Run(ApplicationContext context)
        {
            // If a sync context hasn't been created by now, create
            // a default one
            if (SynchronizationContext.Current == null)
            {
                SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
            }

            RunLoop(false, context);

            // Reset the sync context back to the default
            if (SynchronizationContext.Current is WindowsFormsSynchronizationContext)
            {
                WindowsFormsSynchronizationContext.Uninstall();
            }
        }
Esempio n. 12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FullscreenRenderTarget" /> class.
        /// </summary>
        /// <param name="outputInfo">The target output monitor.</param>
        /// <param name="initialMode">The initial view mode.</param>
        public FullscreenRenderTarget(EngineOutputInfo outputInfo, EngineOutputModeInfo initialMode = default(EngineOutputModeInfo))
        {
            outputInfo.EnsureNotNull(nameof(outputInfo));

            // Check whether we are inside a win.forms application
            System.Windows.Forms.WindowsFormsSynchronizationContext syncContext = SynchronizationContext.Current
                                                                                  as System.Windows.Forms.WindowsFormsSynchronizationContext;
            if (syncContext == null)
            {
                throw new SeeingSharpException($"{nameof(FullscreenRenderTarget)} muss be created inside a Windows.Forms application context!");
            }
            m_syncContext = syncContext;

            //Set confiugration
            m_targetOutput     = outputInfo;
            m_targetOutputMode = initialMode;
            if (m_targetOutputMode.HostOutput != outputInfo)
            {
                m_targetOutputMode = m_targetOutput.DefaultMode;
            }
            m_renderAwaitors = new ThreadSaveQueue <TaskCompletionSource <object> >();

            // Ensure that graphics is initialized
            GraphicsCore.Touch();

            // Create the dummy form
            m_dummyForm = new DummyForm();
            m_dummyForm.SetStyleCustom(ControlStyles.AllPaintingInWmPaint, true);
            m_dummyForm.SetStyleCustom(ControlStyles.ResizeRedraw, true);
            m_dummyForm.SetStyleCustom(ControlStyles.OptimizedDoubleBuffer, false);
            m_dummyForm.SetStyleCustom(ControlStyles.Opaque, true);
            m_dummyForm.SetStyleCustom(ControlStyles.Selectable, true);
            m_dummyForm.SetDoubleBuffered(false);
            m_dummyForm.MouseEnter      += (sender, eArgs) => Cursor.Hide();
            m_dummyForm.MouseLeave      += (sender, eArgs) => Cursor.Show();
            m_dummyForm.HandleDestroyed += OnDummyForm_HandleDestroyed;
            m_dummyForm.GotFocus        += OnDummyForm_GotFocus;
            m_dummyForm.CreateControl();

            // Create and start the renderloop
            m_renderLoop = new RenderLoop(syncContext, this);
            m_renderLoop.Camera.SetScreenSize(m_targetOutputMode.PixelWidth, m_targetOutputMode.PixelHeight);
            m_renderLoop.RegisterRenderLoop();
        }
Esempio n. 13
0
        public Context()
        {
            MainSynchronizationContext = new WindowsFormsSynchronizationContext();
            ThreadExit += new EventHandler(Context_ThreadExit);

            LoadSettings();
            LoadData();

            InstallMenu();

            Mayor.Updated += new Mayor.UpdateDelegate(UpdateCallback);
            if (Mayor.Settings.AutoUpdate)
            {
                RunUpdate();
            }

            UpdateTimer = new System.Timers.Timer(UpdateFrequency * 1000);
            UpdateTimer.Elapsed += new System.Timers.ElapsedEventHandler(CheckTimer_Tick);
            UpdateTimer.Start();
        }
Esempio n. 14
0
        void RunUpdateThread()
        {
            UpdateSynchronizationContext = new WindowsFormsSynchronizationContext();

            SetIconStatus("Checking mail...");

            try
            {
                Mail.RunUpdate();

                Icon.Icon = Mail.Emails.Count > 0 ? Properties.Resources.Unread : Properties.Resources.Read;
                SetIconStatus(Mail.Emails.Count == 0 ? "No unread mail" : Mail.Emails.Count.ToString() + " unread mail");

                LastResult = Response.Success;
            }
            catch (UnauthorizedAccessException)
            {
                UpdateIcon(Properties.Resources.Error, "Invalid credentials");

                if (LastResult != Response.AccessDenied)
                {
                    ShowNotification("Invalid credentials", "The configured email address or password is invalid. Right-click the Gmail Notifier icon and choose Settings to update your credentials.");
                    LastResult = Response.AccessDenied;
                }
            }
            catch (Exception)
            {
                UpdateIcon(Properties.Resources.Error, "Unable to load your inbox");

                if (LastResult != Response.Error)
                {
                    ShowNotification("Unable to load your inbox", "Gmail Notifier was unable to load the contents of your inbox. Make sure you are connected to the internet and verify that you can reach Gmail from your browser.");
                    LastResult = Response.Error;
                }
            }
        }
Esempio n. 15
0
        /// <summary>
        /// Initializes this object.
        /// </summary>
        private void Initialize()
        {
            if (IsUnitTest) return;
            this.uithread = System.Threading.Thread.CurrentThread;

            if (this.synchronizationContext == null)
            {
#if DEBUG
                 // This is a handy place to do this, since the product and all interesting unit tests
                 // must go through this code path.
                 AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(delegate(object sender, UnhandledExceptionEventArgs args)
                 {
                     if (args.IsTerminating)
                     {
                         string s = String.Format(CultureInfo.InvariantCulture, "An unhandled exception is about to terminate the process.  Exception info:\n{0}", args.ExceptionObject.ToString());
                         Debug.Assert(false, s);
                     }
                 });

                 this.captureStackTrace = new StackTrace(true);
#endif
                this.synchronizationContext = new WindowsFormsSynchronizationContext();
            }
            else
            {
                 // Make sure we are always capturing the same thread.
                 Debug.Assert(this.uithread == Thread.CurrentThread);
            }
        }       
Esempio n. 16
0
        private static void RunAppThread(object state)
        {
            var ownMessageLoopMainForm = new Form();
            ownMessageLoopMainForm.ShowInTaskbar = false;
            ownMessageLoopMainForm.Width = 0;
            ownMessageLoopMainForm.Height = 0;
            ownMessageLoopMainForm.Load += ownerForm_Load;

            Application.Run(ownMessageLoopMainForm);

            if (syncContext != null)
            {
                syncContext.Dispose();
                syncContext = null;
            }
        }
		public void AddControl_DifferentThreadInContextUsingConfiguration_UsesAmbientContext()
		{
			var form = new DummyForm();
			var client = Container.Resolve<ClassUsingFormInAmbientContext>();
			ExecuteInThread(() =>
			{
				using (var winCtx = new WindowsFormsSynchronizationContext())
				{
					SynchronizationContext.SetSynchronizationContext(winCtx);
					client.DoWork(form);
				}
			});
			Assert.IsNull(uncaughtException, "Expected no exception");
		}
Esempio n. 18
0
        public static void InvokeOnNewMessageLoop(CallInUIThreadCallback action, params object[] additionalParams)
        {
            if (!hasOwnMessageLoop)
            {
                syncContext = null;
                ThreadPool.QueueUserWorkItem(RunAppThread);
                while (syncContext == null) Thread.Sleep(10);
            }

            if (syncContext != null)
            {
                bool callFinished = false;
                syncContext.Post(new SendOrPostCallback(delegate(object state)
                {
                    action.Invoke(null, additionalParams);
                    callFinished = true;
                }), null);
                while (!callFinished) Thread.Sleep(10);
            }
            else
            {
                action.Invoke(null, additionalParams);
            }
        }
Esempio n. 19
0
        public static void Invoke(CallInUIThreadCallback action, params object[] additionalParams)
        {
            Form appFormWithMessageLoop = Application.OpenForms.Cast<Form>().FirstOrDefault(x => x != null && x.Owner == null);

            if (appFormWithMessageLoop != null && (Application.MessageLoop || hasOwnMessageLoop))
            {
                if (appFormWithMessageLoop.InvokeRequired)
                {
                    appFormWithMessageLoop.Invoke(action, appFormWithMessageLoop, additionalParams);
                }
                else
                {
                    action.Invoke(appFormWithMessageLoop, additionalParams);
                }
            }
            else if (!Application.MessageLoop && syncContext == null)
            {
                if (syncContext == null)
                {
                    ThreadPool.QueueUserWorkItem(RunAppThread);
                    while (syncContext == null) Thread.Sleep(10);
                }

                if (syncContext != null)
                {
                    bool callFinished = false;
                    syncContext.Post(new SendOrPostCallback(delegate(object state)
                    {
                        action.Invoke(appFormWithMessageLoop != null && !appFormWithMessageLoop.InvokeRequired ? appFormWithMessageLoop : null, additionalParams);
                        callFinished = true;
                    }), null);
                    while (!callFinished) Thread.Sleep(10);
                }
                else
                {
                    action.Invoke(appFormWithMessageLoop != null && !appFormWithMessageLoop.InvokeRequired ? appFormWithMessageLoop : null, additionalParams);
                }
            }
            else
            {
                if (syncContext == null)
                {
                    syncContext = new WindowsFormsSynchronizationContext();
                }

                if (syncContext != null)
                {
                    bool callFinished = false;
                    syncContext.Post(new SendOrPostCallback(delegate(object state)
                    {
                        action.Invoke(appFormWithMessageLoop != null && !appFormWithMessageLoop.InvokeRequired ? appFormWithMessageLoop : null, additionalParams);
                        callFinished = true;
                    }), null);
                    while (!callFinished) Thread.Sleep(10);
                }
                else
                {
                    action.Invoke(appFormWithMessageLoop != null && !appFormWithMessageLoop.InvokeRequired ? appFormWithMessageLoop : null, additionalParams);
                }
            }
        }
Esempio n. 20
0
        protected virtual void Dispose(bool disposing)
        {
            if (!disposed)
            {
                if (disposing)
                {
                    if (this.threadInitializedEvent != null)
                    {
                        this.threadInitializedEvent.Dispose();
                        this.threadInitializedEvent = null;
                    }

                    if (this.formsSyncContext != null)
                    {
                        this.formsSyncContext.Dispose();
                        this.formsSyncContext = null;                        
                    }
                }

                disposed = true;
            }
        }
Esempio n. 21
0
        private Thread StartUIThread()
        {
            // Start a new UI thread to run the browser dialog on so that we can block this one and present
            // a synchronous interface to callers.
            Thread uiSubThread = new Thread(
                () =>
                {
                    try
                    {
                        this.formsSyncContext = new WindowsFormsSynchronizationContext();

                        this.dialog = new SilentWindowsFormsAuthenticationDialog(this.OwnerWindow)
                        {
                            NavigationWaitMiliSecs = NavigationWaitMiliSecs
                        };

                        this.dialog.Done += this.UIDoneHandler;

                        this.threadInitializedEvent.Set();

                        this.dialog.AuthenticateAAD(this.RequestUri, this.CallbackUri);

                        // Start and turn control over to the message loop.
                        Application.Run();

                        this.result = this.dialog.Result;
                    }
                    catch (Exception e)
                    {
                        // Catch all exceptions to transfer them to the original calling thread.
                        this.uiException = e;
                    }
                });

            uiSubThread.SetApartmentState(ApartmentState.STA);
            uiSubThread.IsBackground = true;
            uiSubThread.Start();

            return uiSubThread;
        }
Esempio n. 22
0
        public MainForm()
        {
            InitializeComponent();

            //*******************************************************************
            //      MenuForm
            //*******************************************************************
            this.Load += MainForm_Load;

            //Minimum size of the form
            this.MinimumSize = FormMinimumSize;
            this.Text = "Artificial Neural Network";

            //GUI update thread, will be used for updating the form
            this.syncContext = SynchronizationContext.Current as WindowsFormsSynchronizationContext;

            //*****************************************************************************
            //      Tooltip
            //*****************************************************************************
            tooltip = new ToolTip();
            // Set up the delays for the ToolTip.
            tooltip.AutoPopDelay = 5000;
            tooltip.InitialDelay = 1000;
            tooltip.ReshowDelay = 500;
            // Force the ToolTip text to be displayed whether or not the form is active.
            tooltip.ShowAlways = true;


            //*****************************************************************************
            //      Menubar
            //*****************************************************************************
            //Sets the button to disabled
            tsButtonRemove.Enabled = false;

            //*****************************************************************************
            //      Buttons
            //*****************************************************************************
            //Button - Test the neural network
            btnTest.Enabled = false;

            //Button - Stop
            btnStop.Click += BtnStop_Click;
            btnStop.Enabled = false;

            //Button - Train the neural network
            btnTrain.Enabled = false;
            btnTrain.Click += btnTrain_Click;

            //Button - Show Test Matrix
            btnShowTestMatrix.Enabled = false;
            btnShowTestMatrix.Click += btnShowMatrix_Click;

            //Button - Show Train Matrix
            btnShowTrainMatrix.Enabled = false;
            btnShowTrainMatrix.Click += btnShowMatrix_Click;

            //*****************************************************************************
            //      Label tooltips
            //*****************************************************************************
            tooltip.SetToolTip(this.lblIterations, "Maximum iterations for the neural network.");
            tooltip.SetToolTip(this.lblLearnRate, "The difference in the learn rate for each new iteration.");

            //TODO
            tooltip.SetToolTip(this.lblMomentum, "TODO.");
            tooltip.SetToolTip(this.lblProcentage, "TODO.");


            //*****************************************************************************
            //      Numeric up & down
            //*****************************************************************************
            //default values
            numericIterations.Minimum = 1; //10e0
            numericIterations.Value = 1000; //10e3
            numericIterations.Maximum = 1000000; //10e6

            //
            numericLearnrate.Value = (decimal)0.005;
            numericLearnrate.Increment = (decimal)0.005;
            numericLearnrate.Minimum = (decimal)0.005;
            //Maximum?

            //numericMomentum

            numericPercentage.Value = 90;
            numericPercentage.Increment = 1;
            numericPercentage.Minimum = 1;
            numericPercentage.Maximum = 99;

            numericHidden.Value = 10;
            numericHidden.Increment = 1;
            numericHidden.Minimum = 1;
            numericHidden.Maximum = 1000; //10e^3

            //int[] arrayCheck = { 2, 19, 20, 21 }; //TODO: check criticalIndex
            // trainingData = FileReader.CollectJaggedFileDataArray("C://Users//dss10_000//Documents//GitHub//LearningSystemsLabs//Lab1//Data_Training.txt", 4, arrayCheck);
            // btnTrain.Enabled = true;

        

        }
 protected override BindingInfo<IThreadManager> GetThreadManager()
 {
     if (Context.Platform.Platform != PlatformType.WinForms)
         return BindingInfo<IThreadManager>.Empty;
     if (UseSimpleThreadManager)
         return BindingInfo<IThreadManager>.FromType<SynchronousThreadManager>(DependencyLifecycle.SingleInstance);
     return BindingInfo<IThreadManager>.FromMethod((container, list) =>
     {
         var context = SynchronizationContext.Current as WindowsFormsSynchronizationContext;
         if (context == null)
         {
             context = new WindowsFormsSynchronizationContext();
             SynchronizationContext.SetSynchronizationContext(context);
             WindowsFormsSynchronizationContext.AutoInstall = false;
         }
         return new ThreadManager(context);
     }, DependencyLifecycle.SingleInstance);
 }
Esempio n. 24
0
        private void _ApplicationContextThread()
        {
            _applicationContext = _applicationContextThreadInit();
            if (_applicationContext == null) throw new InvalidOperationException();

            _synchronizationContext = new WindowsFormsSynchronizationContext();
            _startupFinished.Set();
            Application.Run(_applicationContext);
        }
Esempio n. 25
0
        private static void StartIpcPipe()
        {
            //todo: impl a set of IPC APIs to perform some cmds. eg.Pause/Resume, Quit...
            //todo: Temporay IPC mechanism.
            var synCtx = new WindowsFormsSynchronizationContext();//note: won't work with `SynchronizationContext.Current`
            var pipeThread = new Thread(() =>
            {
                while (true)
                {
                    using (var server = new System.IO.Pipes.NamedPipeServerStream("WGestures_IPC_API"))
                    {
                        server.WaitForConnection();

                        Debug.WriteLine("Clien Connected");
                        using (var reader = new StreamReader(server))
                        {
                            var cmd = reader.ReadLine();
                            Debug.WriteLine("Pipe CMD=" + cmd);

                            if (cmd == "ShowSettings")
                            {
                                synCtx.Post((s) =>
                                {
                                    Debug.WriteLine("Thread=" + Thread.CurrentThread.ManagedThreadId);
                                    ShowSettings();
                                }, null);
                            }
                        }
                    }
                }
            }) { IsBackground = true };
            pipeThread.Start();
        }
Esempio n. 26
0
		public FrmMain() {
			this.InitializeComponent();


            Closed += (s, e) => { Environment.Exit(0); };


			Thread.CurrentThread.Name = "UIThread";
			base.IsMdiContainer = false;

			var btnNewFrmST = new Button {
				Text = "New Form (Main Thread)",
				Width = 400
			};

			var prevBtn = btnNewFrmST;
			var btnNewFrmMT = new Button {
				Text = "New form does work on its own Thread (The app remains responsive).",
				Top = prevBtn.Top + prevBtn.Height + 10,
				Width = prevBtn.Width
			};

			prevBtn = btnNewFrmMT;
			var btnNewFrmTsk = new Button {
				Text = "New Form (Task)",
				Top = prevBtn.Top + prevBtn.Height + 10,
				Width = prevBtn.Width
			};

			prevBtn = btnNewFrmTsk;
			var btnNewFrmWork = new Button {
				Text = "New form does work on the UI Thread (Hangs the app).",
				Top = prevBtn.Top + prevBtn.Height + 10,
				Width = prevBtn.Width
			};

			prevBtn = btnNewFrmWork;
			var btnNewFrmWorkAsync = new Button {
				Text = "New Form (Does Async work...)",
				Top = prevBtn.Top + prevBtn.Height + 10,
				Width = prevBtn.Width
			};

			// Controls.Add(btnNewFrmST);
			Controls.Add(btnNewFrmMT);
			// Controls.Add(btnNewFrmTsk);
			Controls.Add(btnNewFrmWork);
			// Controls.Add(btnNewFrmWorkAsync);

			var syncctx = new WindowsFormsSynchronizationContext();

			btnNewFrmMT.Click += (sender, args) => {
				Thread t = new Thread(()=> {

                        while(true) {
                            // Shows a new form
                            syncctx.Post(ui => {
                                    // MessageBox.Show("SyncCtx running on thread #" + Thread.CurrentThread.Name);
                                    var frm = new FrmEx();
                                    try {
                                        frm.Show();
                                    }
                                    catch (Exception ex) {
                                        MessageBox.Show($"Catched inside thread ctx.\n{ex.Message}");
                                    }
                                }, 
                                null);

                            // Simulates some work.
                            for(int i=0; i < 10*1000; i++){
                                WriteLine($"Doing work on #{Thread.CurrentThread.Name} => {i}");

                                Thread.Sleep(0);
                            }

                            Application.DoEvents();

                        }
				});

                t.Name = $"#{new Random().Next()}";
				t.Start();
			};

			btnNewFrmST.Click += (sender, args) => {
				var frm = new FrmEx();
				frm.Show();
			};

			btnNewFrmTsk.Click += (sender, args) => {
				Task<int> tsk = new Task<int>(()=> {
					int result;
					try {
						MessageBox.Show("tsk");
						var frm = new FrmEx();
						frm.ShowDialog();
						result = 0;
					}
					catch {
						MessageBox.Show("catched");
						result = 1;
					}
					return result;
				});

				Action<Task<int>> onErr = delegate(Task<int> t) {
					MessageBox.Show(t.Exception.Message);
				};

				tsk.ContinueWith(onErr, TaskContinuationOptions.OnlyOnFaulted);
				tsk.Start();
			};

			btnNewFrmWork.Click += (sender, args) => {
				var frm = new FrmEx();
				frm.Show();
				int count = 0;
				while (true) {
					count++;
					if (count == 10000000) {
						Thread.Sleep(1000);
						count = 0;
					}
                    WriteLine($"Doing work on #{Thread.CurrentThread.Name} => {count}");
				}
			};

			btnNewFrmWorkAsync.Click += (sender, args) => {
				var frm = new FrmEx();
				frm.Show();
				int count = 0;
				Thread t = new Thread(() => {
					while (true) {
						count++;
						if (count == 10000000) {
							Thread.Sleep(1000);
							count = 0;
						}
					}
				});

				t.Start();
			};
		}
Esempio n. 27
0
		/// <summary>
		/// 	Configures default services provided by Quokka.
		/// </summary>
		/// <remarks>
		/// 	Normally you do not have to override this method. Only override if
		/// 	you especially do not want these services available to your program.
		/// </remarks>
		protected virtual void ConfigureDefaultServices()
		{
			if (!ServiceContainer.IsTypeRegistered<IEventBroker>())
			{
				ServiceContainer.RegisterType<IEventBroker, EventBrokerImpl>(ServiceLifecycle.Singleton);
			}

			if (!ServiceContainer.IsTypeRegistered<IDateTimeProvider>())
			{
				ServiceContainer.RegisterType<IDateTimeProvider, DateTimeProvider>(ServiceLifecycle.Singleton);
			}

			if (!ServiceContainer.IsTypeRegistered<IGuidProvider>())
			{
				ServiceContainer.RegisterType<IGuidProvider, GuidProvider>(ServiceLifecycle.Singleton);
			}

			if (!ServiceContainer.IsTypeRegistered<IRegionManager>())
			{
				ServiceContainer.RegisterType<IRegionManager, RegionManager>(ServiceLifecycle.Singleton);
			}

			if (!ServiceContainer.IsTypeRegistered<SynchronizationContext>())
			{
				if (SynchronizationContext.Current == null)
				{
					SynchronizationContext ctx = new WindowsFormsSynchronizationContext();
					ServiceContainer.RegisterInstance(ctx);
				}
				else
				{
					ServiceContainer.RegisterInstance(SynchronizationContext.Current);
				}
			}

			if (!ServiceContainer.IsTypeRegistered<IModalWindowFactory>())
			{
				ServiceContainer.RegisterType<IModalWindowFactory, ModalWindowFactory>(ServiceLifecycle.Singleton);
			}

			if (!ServiceContainer.IsTypeRegistered<IUIMessageBoxView>())
			{
				ServiceContainer.RegisterType<IUIMessageBoxView, MessageBoxView>(ServiceLifecycle.PerRequest);
			}

			if (!ServiceContainer.IsTypeRegistered<Worker>())
			{
				ServiceContainer.RegisterType<Worker>(ServiceLifecycle.PerRequest);
			}

			if (!ServiceContainer.IsTypeRegistered<IErrorReportView>())
			{
				ServiceContainer.RegisterType<IErrorReportView, ErrorReportView>(ServiceLifecycle.PerRequest);
			}
		}
Esempio n. 28
0
        static void ownerForm_Load(object sender, EventArgs e)
        {
            Form form = (Form)sender;
            form.Left = -5000;
            form.Top = -5000;
            form.Hide();

            syncContext = new WindowsFormsSynchronizationContext();

            hasOwnMessageLoop = true;
        }