예제 #1
0
파일: UIThread.cs 프로젝트: zhyifei/wix3
        /// <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);
            }
        }
예제 #2
0
 public static void Run(Action <string[]> mainProc, string[] args)
 {
     //You need to reference System.Windows.Forms
     _syncContext = new WindowsFormsSynchronizationContext();
     EnqueueSyncTask(mainProc, args);
     Application.Run();
 }
예제 #3
0
        public Form1()
        {
            InitializeComponent();
            mSyncContext = SynchronizationContext.Current as WindowsFormsSynchronizationContext;

            Initialize();
        }
예제 #4
0
        private void Tools_thempedit_Click(object sender, EventArgs e)
        {
            if (editcome == null)
            {
                editcome = PlugManager.PlugKernelManager.MainEventProcess("http://www.emed.cc/CodeBuilderStudio/Details/ThempEdit") as BaseCome;
            }
            if (editcome == null)
            {
                return;
            }
            (editcome as global::Main.Interface.ThempEdit).OpenEditViewEvent += new ParameterHander <ThempEdit, PlugEventArgs>(FrmMain_OpenEditViewEvent);
            (editcome as global::Main.Interface.ThempEdit).OpenEditCodeEvent += new ParameterHander <ThempEdit, PlugEventArgs>(FrmMain_OpenEditCodeEvent);
            (editcome as global::Main.Interface.ThempEdit).ShowDemoEvent     += new ParameterHander <ThempEdit, PlugEventArgs>(FrmMain_ShowDemoEvent);
            (editcome as global::Main.Interface.ComeBaseModule.BaseCome).ComeExceptionEvent += new OnExceptionHandler <ComeRestException>(FrmMain_ComeExceptionEvent);
            // (editcome as ISynchronizeInvoke).BeginInvoke(new ThempEditCallBackHandle(SetControlCallBackMethod), null);
            this.Refresh();
            //(editcome as global::Main.Interface.ThempEdit).Invoke(null, null);//一定要同步调用,异步暂未实现,由于三重异步委托导致控件无法归位。
            FrmWait frmwait = new FrmWait();

            frmwait.TopMost = true;
            frmwait.Show();
            frmwait.Refresh();
            SendOrPostCallback callback = _ =>
            {
                frmwait.Close();
            };
            WindowsFormsSynchronizationContext currentcontext = WindowsFormsSynchronizationContext.Current as WindowsFormsSynchronizationContext;

            (editcome as global::Main.Interface.ThempEdit).SynchInvoke(currentcontext, callback);
        }
예제 #5
0
        private static void Run()
        {
            WindowsFormsSynchronizationContext.AutoInstall = false;
            Utilities.EnableMenuShortcutsUnderlining();

            Application.EnableVisualStyles();
            Application.SetHighDpiMode(HighDpiMode.PerMonitorV2);
            Application.SetCompatibleTextRenderingDefault(false);
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

            using (var context = new WindowsFormsSynchronizationContext())
            {
                SynchronizationContext.SetSynchronizationContext(context);
                Application.ThreadException += ThreadExceptionHandler;
                try
                {
                    Environment.ExitCode = 0;
                    context.Post(_ => RunAsync(), null);
                    Application.Run();
                }
                catch (Exception ex)
                {
                    ObserveError(ex);
                }
                finally
                {
                    Application.ThreadException -= ThreadExceptionHandler;
                    SynchronizationContext.SetSynchronizationContext(null);
                }
            }
        }
예제 #6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Application"/> class.
        /// </summary>
        protected Application(ApplicationContext settings)
            : base(settings)
        {
            Settings = settings;

            var uiSynchronizationContextCreated = new AutoResetEvent(false);

            UiThread = new Thread(() =>
            {
                FormsApplication.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                FormsApplication.ThreadException           += new ThreadExceptionEventHandler(Forms_UiUnhandledException);
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(Forms_UnhandledException);

                FormsApplication.EnableVisualStyles();
                FormsApplication.SetCompatibleTextRenderingDefault(false);

                SynchronizationContext.SetSynchronizationContext(UiSynchronizationContext = new WindowsFormsSynchronizationContext());
                uiSynchronizationContextCreated.Set();

                FormsApplication.Run();
            });
            UiThread.SetApartmentState(ApartmentState.STA);
            UiThread.Start();

            uiSynchronizationContextCreated.WaitOne();
        }
 public BrowserController()
 {
     obj = this;
     sc  = new WindowsFormsSynchronizationContext();
     fd  = new FolderBrowserDialog();
     startBrowser(Server.getServer().current_page);
 }
예제 #8
0
        public WinFormsApartment()
        {
            var startTcs = new TaskCompletionSource <TaskScheduler>();

            // start an STA thread with WindowsFormsSynchronizationContext
            // and gets a task scheduler for it
            void threadStart()
            {
                try
                {
                    WindowsFormsSynchronizationContext.AutoInstall = false;
                    Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                    using (var context = new WindowsFormsSynchronizationContext())
                    {
                        SynchronizationContext.SetSynchronizationContext(context);
                        Application.ThreadException += ThreadExceptionHandler;
                        startTcs.TrySetResult(TaskScheduler.FromCurrentSynchronizationContext());
                        try
                        {
                            using (CreateAsyncScope())
                            {
                                Application.Run();
                            }
                        }
                        catch (Exception ex)
                        {
                            AddException(ex);
                        }
                        finally
                        {
                            Application.ThreadException -= ThreadExceptionHandler;
                            SynchronizationContext.SetSynchronizationContext(null);
                            TrySetCompletion();
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (!startTcs.TrySetException(ex))
                    {
                        throw;
                    }
                }
            }

            Task waitForCompletionAsync() =>
            GetCompletionTask().ContinueWith(
                anteTask => { _thread.Join(); return(anteTask); },
                cancellationToken: CancellationToken.None,
                TaskContinuationOptions.ExecuteSynchronously,
                scheduler: TaskScheduler.Default).Unwrap();

            _thread = new Thread(threadStart);
            _thread.SetApartmentState(ApartmentState.STA);
            _thread.IsBackground = true;
            _thread.Start();

            this.TaskScheduler = startTcs.Task.Result;
            this.Completion    = waitForCompletionAsync();
        }
예제 #9
0
        public override string GetCustomUI(string _)
        {
            try
            {
                SynchronizationContext windowsFormsSynchronizationContext = new WindowsFormsSynchronizationContext();
                SynchronizationContext.SetSynchronizationContext(windowsFormsSynchronizationContext);

                this.AppConfig = new AppConfig();

                var restClient = new RestClient(this.AppConfig.AllorsDatabaseAddress).UseNewtonsoftJson();
                this.database = new RemoteDatabase(() => restClient);

                var objectFactory = new ObjectFactory(MetaPopulation.Instance, typeof(User));
                var workspace     = new Workspace(objectFactory);
                this.Client         = new Client(this.database, workspace);
                this.Program        = new Program(new ServiceLocator(), this.Client);
                this.AddIn          = new AddIn((InteropApplication)ExcelDnaUtil.Application, this.Program, this);
                this.Authentication = new Authentication(this.Program, this.database, this.Client, this.AppConfig);

                return(RibbonResources.Ribbon);
            }
            catch (Exception e)
            {
                e.Handle();
                throw;
            }
        }
예제 #10
0
        private void processInvoice(string dir, string invoiceno, int rowNum)
        {
            WindowsFormsSynchronizationContext mUiContext = this.mUiContext;
            SendOrPostCallback d        = new SendOrPostCallback(this.UpdateGridText);
            string             filename = dir + Path.DirectorySeparatorChar.ToString() + invoiceno + ".pdf";
            InvoiceInfo        objA     = this.ReadPDF(filename, rowNum);

            if (!ReferenceEquals(objA, null))
            {
                objA.invFile = filename;
                Tuple <bool, string> tuple = objA.ValidateReadedData(invoiceno);
                if (!tuple.Item1)
                {
                    mUiContext.Post(d, new Tuple <int, string>(rowNum, tuple.Item2));
                }
                else
                {
                    Tuple <bool, string> tuple2 = objA.FindFiles(dir, objA);
                    if (!tuple2.Item1)
                    {
                        mUiContext.Post(d, new Tuple <int, string>(rowNum, tuple2.Item2));
                    }
                    else
                    {
                        InvoicePrcessor prcessor = new InvoicePrcessor();
                        string          str2     = prcessor.ProcessInvoice(objA);
                        mUiContext.Post(d, new Tuple <int, string>(rowNum, str2));
                        prcessor.Dispose();
                    }
                }
            }
        }
예제 #11
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;

            mapControl.OnPolygonEnter += MapControl_OnPolygonEnter;
            mapControl.OnPolygonLeave += MapControl_OnPolygonLeave;

            //mapControl.OnRouteClick += MapControl_OnRouteClick;
            mapControl.OnRouteEnter += MapControl_OnRouteEnter;
            mapControl.OnRouteLeave += MapControl_OnRouteLeave;
        }
예제 #12
0
파일: UIThread.cs 프로젝트: ctmal/vixen
		private void _ApplicationContextThread() {
			_applicationContext = _applicationContextThreadInit();
			if(_applicationContext == null) throw new InvalidOperationException();

			_synchronizationContext = new WindowsFormsSynchronizationContext();
			Application.Run(_applicationContext);
		}
예제 #13
0
        void Main.Interface.ThempEdit.SynchInvoke(WindowsFormsSynchronizationContext winformcontext, SendOrPostCallback callbackmethod)
        {
            object result = OpenEdieView();

            //客户端可以通过捕获事件来拿到对象,消除调用和设置之间的耦合
            _openeditviewevent(this, (result as Main.Interface.ComeBaseModule.PlugEventArgs));
            winformcontext.Post(callbackmethod, null);
        }
예제 #14
0
        public HomeUserControl()
        {
            synchronizationContext = (WindowsFormsSynchronizationContext)SynchronizationContext.Current;

            InitializeComponent();

            MessageBus.Bus.Instance.Subscribe <SystemStatusUpdateEvent>(this, OnSystemStatusUpdateEvent);
        }
예제 #15
0
 public void RunAsUIThread(Action beforeRun = null)
 {
     context = new WindowsFormsSynchronizationContext();
     contextInited.Set();
     Application.EnableVisualStyles();
     beforeRun?.Invoke();
     Application.Run();
 }
예제 #16
0
        protected override IRibbonExtensibility CreateRibbonExtensibilityObject()
        {
            SynchronizationContext windowsFormsSynchronizationContext = new WindowsFormsSynchronizationContext();

            SynchronizationContext.SetSynchronizationContext(windowsFormsSynchronizationContext);

            this.Ribbon = new Ribbon();
            return(this.Ribbon);
        }
예제 #17
0
파일: Program.cs 프로젝트: wuweidev/gitw
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            AppContext  = new GitApplicationContext();
            SyncContext = new WindowsFormsSynchronizationContext();

            string pathOrCommitish = args.Length > 0 ? args[0] : null;
            string fullPath        = pathOrCommitish == null ? Environment.CurrentDirectory : Path.GetFullPath(pathOrCommitish);

            if (Directory.Exists(fullPath) && !fullPath.EndsWith("\\"))
            {
                fullPath += "\\";
            }

            // Repository.Discover doesn't work with paths that don't exist.
            // Traverse up the tree to find an existing directory.
            string discoverPath = fullPath;

            while (!Directory.Exists(discoverPath))
            {
                discoverPath = Directory.GetParent(discoverPath).FullName;
            }

            string repoRoot = Repository.Discover(discoverPath);

            if (repoRoot == null)
            {
                return;
            }

            using (var repo = new Repository(repoRoot))
            {
                Form form;
                var  commit = TryLookupCommit(repo, fullPath, pathOrCommitish);
                if (commit != null)
                {
                    fullPath = Environment.CurrentDirectory;
                    if (!fullPath.EndsWith("\\"))
                    {
                        fullPath += "\\";
                    }

                    var gitLog = new GitLog(repo, fullPath, Constants.MaxCommits);
                    form = new GitCommitForm(gitLog, commit);
                }
                else
                {
                    form = new GitLogForm(repo, fullPath);
                }

                AppContext.NewForm(form);

                Application.Run(AppContext);
            }
        }
예제 #18
0
        public WinFormsApplication()
        {
            App.EnableVisualStyles();
            App.SetCompatibleTextRenderingDefault(false);

            Factory = new WinFormsUiFactory();
            SynchronizationContext = new WindowsFormsSynchronizationContext();

            Application.OpenWindows.AllWindowsClosed += Application_AllWindowsClosed;
        }
예제 #19
0
        public void SomeProblemWithGetAwaiterGetResult()
        {
            var blockingSyncContext = new WindowsFormsSynchronizationContext();

            SynchronizationContext.SetSynchronizationContext(blockingSyncContext);
            var theValue = AsyncMethods
                           .WaitASecondAndReturnAValueAsync("this too is doomed")
                           .GetAwaiter()
                           .GetResult();
        }
예제 #20
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();
        }
예제 #21
0
 /// <summary>
 /// Shutdown all CEF instances
 /// </summary>
 internal static void Shutdown()
 {
     using (var syncObj = new WindowsFormsSynchronizationContext()) {
         syncObj.Send(o => {
             if (Cef.IsInitialized)
             {
                 Cef.Shutdown();
             }
         }, new object());
     }
 }
예제 #22
0
        private SynchronizationContext getCurrentContext()
        {
            var context = SynchronizationContext.Current;

            if (context == null)
            {
                context = new WindowsFormsSynchronizationContext();
                SynchronizationContext.SetSynchronizationContext(context);
            }
            return(SynchronizationContext.Current);
        }
예제 #23
0
 public Form1()
 {
     InitializeComponent();
     this.DoubleBuffered = true;
     refreshTaskList();
     if (m_GuiThread == null)
     {
         m_GuiThread = new WindowsFormsSynchronizationContext(); //rembers that the gui thread is this because we init it from the c'tor
     }
     m_RefreshThread = new Thread(RefreshTaskListThread);        //so the thread now which function to activeted once he stratredd
     m_RefreshThread.Start();
 }
예제 #24
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;
        }
예제 #25
0
        static void ownerForm_Load(object sender, EventArgs e)
        {
            Form form = (Form)sender;

            form.Left = -5000;
            form.Top  = -5000;
            form.Hide();

            DebugTrace.TraceInfo("UIThreadCaller is creating new WindowsFormsSynchronizationContext on the newly created MessageLoop thread.");
            syncContext = new WindowsFormsSynchronizationContext();

            hasOwnMessageLoop = true;
        }
예제 #26
0
        private void _FormThread()
        {
            _form = _formThreadInit();
            if (_form == null)
            {
                throw new InvalidOperationException();
            }

            _synchronizationContext = new WindowsFormsSynchronizationContext();
            _applicationContext     = new ApplicationContext(_form);
            _startupFinished.Set();
            Application.Run(_applicationContext);
        }
예제 #27
0
        public void HowDoIFixThisDeadLockByUsingConfigureAwaitFalse()
        {
            var blockingSyncContext = new WindowsFormsSynchronizationContext();

            SynchronizationContext.SetSynchronizationContext(blockingSyncContext);

            var theValue = AsyncMethods
                           .WaitASecondAndReturnAValueAsyncAwaitFalse("this works around it")
                           .GetAwaiter()
                           .GetResult();

            Assert.AreEqual("this works around it", theValue);
        }
예제 #28
0
        /// <summary>
        /// UI thread start.
        /// </summary>
        private void UiThreadStart()
        {
            FormsApplication.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            FormsApplication.ThreadException           += new ThreadExceptionEventHandler(Forms_UiUnhandledException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(Forms_UnhandledException);

            FormsApplication.EnableVisualStyles();
            FormsApplication.SetCompatibleTextRenderingDefault(false);

            SynchronizationContext.SetSynchronizationContext(UiSynchronizationContext = new WindowsFormsSynchronizationContext());
            UiSynchronizationContextCreated.Set();

            FormsApplication.Run();
        }
        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");
        }
예제 #30
0
        public void ItCreatesADeadLockWhenCertainSyncContextsGetInvolved()
        {
            var blockingSyncContext = new WindowsFormsSynchronizationContext();

            SynchronizationContext.SetSynchronizationContext(blockingSyncContext);

            // Result is invoked on the same thread as the blocking sync context
            // Because the sync context blocked when calling the async method,
            // The call to result is deadlocked as it's waiting for the original call
            // to release the thread.
            // A way to see this visually is to execute this from a GUI, it would become non responsive.
            var theValue = AsyncMethods
                           .WaitASecondAndReturnAValueAsync("this is doomed to deadlock")
                           .Result;
        }