コード例 #1
0
ファイル: App.xaml.cs プロジェクト: artgo/CefSharp
        public App()
        {
            _exceptionHandler = CurrentDomainOnUnhandledException;

            var currentDomain = AppDomain.CurrentDomain;
            currentDomain.UnhandledException += _exceptionHandler;
        }
コード例 #2
0
        public static void Initialize() {
            if (_callback != null)
                return;

            _callback = new UnhandledExceptionEventHandler(On_UnhandledException);
            AppDomain.CurrentDomain.UnhandledException += _callback;
        }
コード例 #3
0
        public static void RegisterAppDomainUnhandledExceptionHandler(this ExceptionlessClient client, AppDomain appDomain = null) {
            if (appDomain == null)
                appDomain = AppDomain.CurrentDomain;

            if (_onAppDomainUnhandledException == null)
                _onAppDomainUnhandledException = (sender, args) => {
                    var exception = args.ExceptionObject as Exception;
                    if (exception == null)
                        return;

                    var contextData = new ContextData();
                    contextData.MarkAsUnhandledError();
                    contextData.SetSubmissionMethod("AppDomainUnhandledException");

                    exception.ToExceptionless(contextData, client).Submit();

                    // process queue immediately since the app is about to exit.
                    client.ProcessQueue();
                };

            try {
                appDomain.UnhandledException -= _onAppDomainUnhandledException;
                appDomain.UnhandledException += _onAppDomainUnhandledException;
            } catch (Exception ex) {
                client.Configuration.Resolver.GetLog().Error(typeof(ExceptionlessClientExtensions), ex, "An error occurred while wiring up to the unhandled exception event. This will happen when you are not running under full trust.");
            }
        }
コード例 #4
0
        public void SetGlobalErrorHandler( UnhandledExceptionEventHandler handler )
        {
            if( errorHandler != null ) AppDomain.CurrentDomain.UnhandledException -= errorHandler;

            errorHandler = handler;

            if( errorHandler != null ) AppDomain.CurrentDomain.UnhandledException += errorHandler;
        }
コード例 #5
0
        public CommanderService()
        {
            _unhandledExceptionEventHandler = new UnhandledExceptionEventHandler(CurrentDomainUnhandledException);
            AppDomain.CurrentDomain.UnhandledException += _unhandledExceptionEventHandler;

            InitializeComponent();

            _commanderManager = CommanderManagerFactory.Instance.CreateCommandManager();            
        }
コード例 #6
0
ファイル: test.cs プロジェクト: mono/gert
	static void Main ()
	{
		DateTime start;
		TimeSpan elapsed;

		UnhandledExceptionEventHandler uhe = new UnhandledExceptionEventHandler (OnUnhandledException);

		Application.ThreadException += new ThreadExceptionEventHandler (OnThreadException);
		AppDomain.CurrentDomain.UnhandledException += uhe;

		_exceptionFile = Path.Combine (AppDomain.CurrentDomain.BaseDirectory,
			"unhandled");
		_successFile = Path.Combine (AppDomain.CurrentDomain.BaseDirectory,
			"success");

		_failInCtor = false;
		start = DateTime.Now;
		Application.Run (new MainForm ());
		elapsed = (DateTime.Now - start);

		AppDomain.CurrentDomain.UnhandledException -= uhe;

		Assert.IsTrue (elapsed.TotalMilliseconds > 2000, "#A1");
		Assert.IsTrue (elapsed.TotalMilliseconds < 4000, "#A2");
		Assert.AreEqual (2, _events.Count, "#A3");
		Assert.AreEqual ("Finally", _events [0], "#A4");
		Assert.AreEqual ("ThreadException:MWF | MyException", _events [1], "#A5");
		Assert.IsFalse (File.Exists (_exceptionFile), "#A6");

		AppDomain.CurrentDomain.UnhandledException += uhe;
		_events.Clear ();

		_failInCtor = true;
		start = DateTime.Now;
		try {
			Application.Run (new MainForm ());
			Assert.Fail ("#B1");
		} catch (Exception ex) {
			elapsed = (DateTime.Now - start);

			AppDomain.CurrentDomain.UnhandledException -= uhe;

			Assert.AreEqual (typeof (MyException), ex.GetType (), "#B2");
			Assert.IsNull (ex.InnerException, "#B3");
			Assert.AreEqual ("MWF", ex.Message, "#B4");

			Assert.IsTrue (elapsed.TotalMilliseconds < 1000, "#B5");
			Assert.AreEqual (1, _events.Count, "#B6");
			Assert.AreEqual ("Finally", _events [0], "#B7");
			Assert.IsFalse (File.Exists (_exceptionFile), "#B8");

			AppDomain.CurrentDomain.UnhandledException += uhe;
			File.Create (_successFile).Close ();

			throw;
		}
	}
コード例 #7
0
		public void Dispose()
		{
			if ( handler != null )
			{
				AppDomain.CurrentDomain.UnhandledException -= handler;
				handler = null;
			}

			System.GC.SuppressFinalize( this );
		}
コード例 #8
0
        public static void UnregisterAppDomainUnhandledExceptionHandler(this ExceptionlessClient client, AppDomain appDomain = null) {
            if (_onAppDomainUnhandledException == null)
                return;

            if (appDomain == null)
                appDomain = AppDomain.CurrentDomain;

            appDomain.UnhandledException -= _onAppDomainUnhandledException;
            _onAppDomainUnhandledException = null;
        }
コード例 #9
0
ファイル: App.xaml.cs プロジェクト: heartszhang/famous
        private void WireUnhandledExceptionHandlers()
        {
            var h = new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            AppDomain.CurrentDomain.UnhandledException += h.MakeWeakSpecial(x => AppDomain.CurrentDomain.UnhandledException -= x);

            var h2 = new  System.Windows.Threading.DispatcherUnhandledExceptionEventHandler(Dispatcher_UnhandledException);
            Dispatcher.UnhandledException += h2.MakeWeakSpecial(x => Dispatcher.UnhandledException -= x);

            var h3 = new EventHandler<UnobservedTaskExceptionEventArgs>(TaskScheduler_UnobservedTaskException);
            TaskScheduler.UnobservedTaskException += h3.MakeWeak(x => TaskScheduler.UnobservedTaskException -= x);
        }
コード例 #10
0
ファイル: App.xaml.cs プロジェクト: Nodios/Games-Store
        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            // If false saves user data locally
            saveToCloud = false;

            InitializeComponent();
            Suspending += OnSuspending;

            // Event subscriber for unhandled events
            UnhandledException += new UnhandledExceptionEventHandler(unhandledException);
        }
コード例 #11
0
        /// <summary>
        /// Hooks up a handler to execute when an uncaught exception is detected
        /// </summary>
        /// <param name="actionOnException">The action to execute, taking as parameters the uncaught exception
        /// and a flag indicating if the runtime is ending</param>
        public void InstallHandler(Action<Exception, bool> actionOnException)
        {
            // If any existing handlers are installed, remove them first
            if (appDomainHandler != null || runOnUnhandledException != null)
                UninstallHandler();

            // Set up references to the handlers
            runOnUnhandledException = actionOnException;
            appDomainHandler = NotifyExceptionHandler;

        }
コード例 #12
0
        /// <summary>
        /// Removes any handler setup to run when an uncaught exception is detected
        /// </summary>
        public void UninstallHandler()
        {
            // Unhook the app domain exception handler, if there is one
            if (appDomainHandler != null)
            {
                AppDomain.CurrentDomain.UnhandledException -= appDomainHandler;
                appDomainHandler = null;
            }

            // Clear the notify action
            runOnUnhandledException = null;
        }
コード例 #13
0
ファイル: TestBase.cs プロジェクト: AqlaSolutions/runsharp
        public void UnhandledExceptionRegistering()
        {
            _exceptions.Clear();
            UnhandledExceptionCheck = DefaultExceptionCheck;
            _unhandledExceptionHandler = (s, e) =>
                {
                    _exceptions.Add(e.ExceptionObject);

                    Debug.WriteLine(e.ExceptionObject);
                };

            AppDomain.CurrentDomain.UnhandledException += _unhandledExceptionHandler;
        }
コード例 #14
0
ファイル: test-async-19.cs プロジェクト: nobled/mono
	public static int Main ()
	{
		ManualResetEvent mre = new ManualResetEvent (false);
		Test (mre);

		var handler = new UnhandledExceptionEventHandler (CurrentDomain_UnhandledException);
		AppDomain.CurrentDomain.UnhandledException += handler;
		try {
			mre.Set ();

			if (!caught.WaitOne (1000))
				return 1;

			return 0;
		} finally {
			AppDomain.CurrentDomain.UnhandledException -= handler;
		}
	}
コード例 #15
0
ファイル: CircuitHost.cs プロジェクト: pengge/testasp.net
        internal void InitializeCircuitAfterPrerender(UnhandledExceptionEventHandler unhandledException)
        {
            if (!_initialized)
            {
                _initialized        = true;
                UnhandledException += unhandledException;
                var uriHelper = (RemoteUriHelper)Services.GetRequiredService <IUriHelper>();
                if (!uriHelper.HasAttachedJSRuntime)
                {
                    uriHelper.AttachJsRuntime(JSRuntime);
                }

                var navigationInterception = (RemoteNavigationInterception)Services.GetRequiredService <INavigationInterception>();
                if (!navigationInterception.HasAttachedJSRuntime)
                {
                    navigationInterception.AttachJSRuntime(JSRuntime);
                }
            }
        }
コード例 #16
0
 // Token: 0x0601564C RID: 87628 RVA: 0x0056D0D0 File Offset: 0x0056B2D0
 private static void _UnregisterExceptionHandler()
 {
     try
     {
         Application.RegisterLogCallback(null);
         AppDomain currentDomain = AppDomain.CurrentDomain;
         if (BuglyAgent.< > f__mg$cache2 == null)
         {
             BuglyAgent.< > f__mg$cache2 = new UnhandledExceptionEventHandler(BuglyAgent._OnUncaughtExceptionHandler);
         }
         currentDomain.UnhandledException -= BuglyAgent.< > f__mg$cache2;
         BuglyAgent.DebugLog(null, "Unregister the log callback in unity {0}", new object[]
         {
             Application.unityVersion
         });
     }
     catch
     {
     }
 }
コード例 #17
0
        public void FinalizerCatchesInvalidComObjectExceptionToPreventErrorsWhenVisualStudioShutsDown()
        {
            object exceptionObject = null;

            UnhandledExceptionEventHandler unhandledExceptionHandler = (sender, args) => exceptionObject = args.ExceptionObject;

            AppDomain.CurrentDomain.UnhandledException += unhandledExceptionHandler;
            try
            {
                this.extenderSite.NotifyDelete = cookie => { throw new InvalidComObjectException(); };
                new BrowseObjectExtender(this.dte, this.projectItem, this.extenderSite, 42);
                GC.Collect(2, GCCollectionMode.Forced, blocking: true);
                GC.WaitForPendingFinalizers();
            }
            finally
            {
                AppDomain.CurrentDomain.UnhandledException -= unhandledExceptionHandler;
            }

            Assert.IsNull(exceptionObject);
        }
        public void TelemetryInitializersFromConfigurationActiveAreUsedForSending()
        {
            bool called = false;
            var  telemetryInitializer = new StubTelemetryInitializer {
                OnInitialize = item => called = true
            };

            TelemetryConfiguration.Active.TelemetryInitializers.Add(telemetryInitializer);

            UnhandledExceptionEventHandler handler = null;

            using (var module = new UnhandledExceptionTelemetryModule(
                       h => handler = h,
                       _ => { },
                       new InMemoryChannel()))
            {
                handler.Invoke(null, new UnhandledExceptionEventArgs(null, true));
            }

            Assert.True(called);
        }
コード例 #19
0
        public RunResponse Run(RunRequest r)
        {
            EventListenerWrapper listenerWrapper = new EventListenerWrapper(server);

            UnhandledExceptionEventHandler exceptionHandler = (object sender, UnhandledExceptionEventArgs e) => {
                var ex = e.ExceptionObject;
                File.WriteAllText(r.CrashLogFile, e.ToString());
            };

            AppDomain.CurrentDomain.UnhandledException += exceptionHandler;
            try {
                var res = Run(listenerWrapper, r.NameFilter, r.Path, r.SuiteName, r.SupportAssemblies, r.TestRunnerType, r.TestRunnerAssembly);
                res = res.SelectSingleNode("test-suite");
                return(new RunResponse()
                {
                    Result = listenerWrapper.GetLocalTestResult(res)
                });
            } finally {
                AppDomain.CurrentDomain.UnhandledException -= exceptionHandler;
            }
        }
コード例 #20
0
        public async Task TestImportMalformedDatabase()
        {
            bool exceptionThrown = false;
            UnhandledExceptionEventHandler setException = (_, __) => exceptionThrown = true;

            using (HeadlessGameHost host = new CleanRunHeadlessGameHost())
            {
                try
                {
                    AppDomain.CurrentDomain.UnhandledException += setException;

                    var osu = loadOsu(host, true);

                    using (var ms = new MemoryStream())
                    {
                        using (var bw = new BinaryWriter(ms, Encoding.UTF8, true))
                        {
                            for (int i = 0; i < 10000; i++)
                            {
                                bw.Write((byte)i);
                            }
                        }

                        ms.Seek(0, SeekOrigin.Begin);

                        await osu.CollectionManager.Import(ms);
                    }

                    Assert.That(host.UpdateThread.Running, Is.True);
                    Assert.That(exceptionThrown, Is.False);
                    Assert.That(osu.CollectionManager.Collections.Count, Is.EqualTo(0));
                }
                finally
                {
                    host.Exit();
                    AppDomain.CurrentDomain.UnhandledException -= setException;
                }
            }
        }
コード例 #21
0
        public static void RegisterAppDomainUnhandledExceptionHandler(this ExceptionlessClient client)
        {
            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }

            if (_onAppDomainUnhandledException == null)
            {
                _onAppDomainUnhandledException = (sender, args) => {
                    var exception = args.ExceptionObject as Exception;
                    if (exception == null)
                    {
                        return;
                    }

                    var contextData = new ContextData();
                    contextData.MarkAsUnhandledError();
                    contextData.SetSubmissionMethod("AppDomainUnhandledException");

                    exception.ToExceptionless(contextData, client).Submit();

                    // process queue immediately since the app is about to exit.
                    client.ProcessQueue();

                    if (client.Configuration.SessionsEnabled)
                    {
                        client.SubmitSessionEnd();
                    }
                };
            }

            try {
                AppDomain.CurrentDomain.UnhandledException -= _onAppDomainUnhandledException;
                AppDomain.CurrentDomain.UnhandledException += _onAppDomainUnhandledException;
            } catch (Exception ex) {
                client.Configuration.Resolver.GetLog().Error(typeof(ExceptionlessClientExtensions), ex, "An error occurred while wiring up to the unhandled exception event. This will happen when you are not running under full trust.");
            }
        }
コード例 #22
0
        private void InitDisposableMembers(NameValueCollection config)
        {
            bool dispose = true;

            try
            {
                try
                {
                    if (_countersSupported)
                    {
                        _perfCounters = new Counters(_name);
                    }
                }
                catch
                {
                    // ignore exceptions from perf counters
                }
                for (int i = 0; i < _storeCount; i++)
                {
                    _storeRefs[i] = new GCHandleRef <MemoryCacheStore>(new MemoryCacheStore(this, _perfCounters));
                }
                _stats = new MemoryCacheStatistics(this, config);
                AppDomain    appDomain         = Thread.GetDomain();
                EventHandler onAppDomainUnload = new EventHandler(OnAppDomainUnload);
                appDomain.DomainUnload += onAppDomainUnload;
                _onAppDomainUnload      = onAppDomainUnload;
                UnhandledExceptionEventHandler onUnhandledException = new UnhandledExceptionEventHandler(OnUnhandledException);
                appDomain.UnhandledException += onUnhandledException;
                _onUnhandledException         = onUnhandledException;
                dispose = false;
            }
            finally
            {
                if (dispose)
                {
                    Dispose();
                }
            }
        }
コード例 #23
0
    public static int Main()
    {
        ManualResetEvent mre = new ManualResetEvent(false);

        Test(mre);

        var handler = new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

        AppDomain.CurrentDomain.UnhandledException += handler;
        try {
            mre.Set();

            if (!caught.WaitOne(1000))
            {
                return(1);
            }

            return(0);
        } finally {
            AppDomain.CurrentDomain.UnhandledException -= handler;
        }
    }
コード例 #24
0
        private void RunTests(ITestFilter filter)
        {
            DateTime startTime = DateTime.Now;

            var crashHandler = new UnhandledExceptionEventHandler(TopLevelHandler);

            AppDomain.CurrentDomain.UnhandledException += crashHandler;

            ITestResult result = runner.Run(this, filter);

            new ResultReporter(result, writer).ReportResults();
            string resultFile   = commandLineOptions.ResultFile;
            string resultFormat = commandLineOptions.ResultFormat;

            this.Failure = (result.ResultState == ResultState.Failure);

            if (resultFile != null || commandLineOptions.ResultFormat != null)
            {
                if (resultFile == null)
                {
                    resultFile = "TestResult.xml";
                }

                if (resultFormat == "nunit2")
                {
                    new NUnit2XmlOutputWriter(startTime).WriteResultFile(result, resultFile);
                }
                else
                {
                    new NUnit3XmlOutputWriter(startTime).WriteResultFile(result, resultFile);
                }

                Console.WriteLine();
                Console.WriteLine("Results saved as {0}.", resultFile);
            }

            AppDomain.CurrentDomain.UnhandledException -= crashHandler;
        }
コード例 #25
0
    public void UnhandledExceptionRegistering()
    {
        _exceptions.Clear();
        UnhandledExceptionCheck    = DefaultExceptionCheck;
        _unhandledExceptionHandler = (s, e) =>
        {
            _exceptions.Add(e.ExceptionObject);

            Debug.WriteLine(e.ExceptionObject);
        };

        AppDomain.CurrentDomain.UnhandledException += _unhandledExceptionHandler;


        if (_validateInitialized)
        {
            return;
        }
        _validateInitialized = true;
#if !PRECOMPILE_PROJECT
        RuntimeTypeModel.ValidateDll += RuntimeTypeModel_ValidateDll;
#endif
    }
コード例 #26
0
        public void Scheduler_BigStepForHumanKindSmallStepForTimerKind()
        {
            var err = default(Exception);

            var h = new UnhandledExceptionEventHandler((o, e) =>
            {
                err = (Exception)e.ExceptionObject;
            });

            try
            {
                AppDomain.CurrentDomain.UnhandledException += h;

                using var ph = PhysicalScheduler.Create();
                using var lg = new LogicalScheduler(ph);

                // The BCL has a limit on 0xfffffffe milliseconds, which is some 49 days (see Worker.NormalizeForTimer).
                // If not handled correctly in Worker.cs, those attempts at scheduling would cause the worker to die.
                lg.Schedule(TimeSpan.FromDays(50), ActionTask.Create(_ => true, 1));
                lg.Schedule(DateTimeOffset.Now.AddDays(50), ActionTask.Create(_ => true, 1));

                // Ensure disposal doesn't happen before the worker thread had a chance to evaluate timer expirations,
                // which is what would cause the test process to die on an invalid call to Timer.Change.
                var e = new ManualResetEvent(false);
                lg.Schedule(ActionTask.Create(_ => { e.Set(); return(true); }, 1));
                e.WaitOne();
            }
            finally
            {
                AppDomain.CurrentDomain.UnhandledException -= h;
            }

            if (err != null)
            {
                ExceptionDispatchInfo.Capture(err).Throw();
            }
        }
コード例 #27
0
ファイル: Game1.cs プロジェクト: pilotdes/Traffic-Warden
        public Game1()
        {
            handler =
                new UnhandledExceptionEventHandler(Target);
            try
            {
                outWriter.WriteLine(DateTime.Now.ToLongDateString() + ", " + DateTime.Now.ToLongTimeString());
                PrintToOutput("Starting Program");
                graphics = new GraphicsDeviceManager(this);
                Content.RootDirectory = "Content";
                guiManager = new GuiManager(Services);
                inputManager = new InputManager(Services, Window.Handle);
                Components.Add(this.inputManager);
                Components.Add(this.guiManager);
                this.guiManager.DrawOrder = 1000;
                IsMouseVisible = true;

                PrintToOutput("Finished Starting Program");
            }
            catch (Exception e)
            {
                handler.Invoke(e, new UnhandledExceptionEventArgs(e, true));
            }
        }
コード例 #28
0
        public static void ExceptionEventHandlerTest()
        {
            bool wasCalled = false;

            UnhandledExceptionEventHandler unhandledExceptionEventHandler = (s, e) =>
            {
                if (!wasCalled)
                {
                    wasCalled = true;
                }
            };

            mBotBadResponse.GetUpdatesError += unhandledExceptionEventHandler;

            do
            {
                mBotBadResponse.StartCheckingUpdates();
            } while (!wasCalled);

            Assert.True(wasCalled);

            mBotBadResponse.StopCheckUpdates();
            mBotBadResponse.GetUpdatesError -= unhandledExceptionEventHandler;
        }
コード例 #29
0
        public int TheRealTest()
        {
            // Regression test for https://github.com/mono/mono/issues/19166
            //
            // Check that if in a call to
            // t.GetAwaiter().OnCompleted(cb) the callback cb
            // throws, that the exception's stack trace includes
            // the method that threw and not just the task
            // machinery's frames.

            // Calling "WhenCompleted" will throw "SpecialExn"
            //
            // If "OnUhandled" is installed as an unhandled exception handler, it will
            //  capture the stack trace of the SpecialExn and allow WaitForExn() to finish waiting.
            // The stack trace is expected to include ThrowerMethodInfo

            var helper = this;
            var d      = new UnhandledExceptionEventHandler(helper.OnUnhandled);

            AppDomain.CurrentDomain.UnhandledException += d;

            // this is TaskToApm.Begin (..., callback) where the callback is helper.WhenCompleted
            Task.Delay(100).GetAwaiter().OnCompleted(helper.WhenCompleted);

            var wasSet = helper.WaitForExn(10000);              // wait upto 10 seconds for the task to throw

            AppDomain.CurrentDomain.UnhandledException -= d;

            if (!wasSet)
            {
                Console.WriteLine("event not set, no exception thrown?");
                return(1);
            }

            return(0);
        }
コード例 #30
0
ファイル: Program.cs プロジェクト: WildGenie/UO98
        internal static void Run(bool respawn)
        {
            if (m_MultiConOut == null)
            {
                Console.SetOut(m_MultiConOut = new MultiTextWriter(Console.Out, new Log(GetLogNameAndBackupExisting("..\\Logs", "Console.log"))));
            }

            if (UnhandledExceptionHandler == null)
            {
                AppDomain.CurrentDomain.UnhandledException += (UnhandledExceptionHandler = new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException));
            }

            CompileScripts();

            if (process == null)
            {
                process = new ServerProcess(WorkingDirectory);
                process.OnProcessExited += new EventHandler <ServerProcess.OnExitedEventArgs>(process_OnProcessExited);
            }

            try
            {
                do
                {
                    process.Start();
                    while (process.IsRunning && !isclosing)
                    {
                        Thread.Sleep(250);
                    }
                } while(respawn && !isclosing);
            }
            finally
            {
                process.Stop();
            }
        }
コード例 #31
0
 private void InitDisposableMembers(NameValueCollection config)
 {
     bool flag = true;
     try
     {
         try
         {
             this._perfCounters = new PerfCounters(this._name);
         }
         catch
         {
         }
         for (int i = 0; i < this._stores.Length; i++)
         {
             this._stores[i] = new MemoryCacheStore(this, this._perfCounters);
         }
         this._stats = new MemoryCacheStatistics(this, config);
         AppDomain domain = Thread.GetDomain();
         EventHandler handler = new EventHandler(this.OnAppDomainUnload);
         domain.DomainUnload += handler;
         this._onAppDomainUnload = handler;
         UnhandledExceptionEventHandler handler2 = new UnhandledExceptionEventHandler(this.OnUnhandledException);
         domain.UnhandledException += handler2;
         this._onUnhandledException = handler2;
         flag = false;
     }
     finally
     {
         if (flag)
         {
             this.Dispose();
         }
     }
 }
コード例 #32
0
 static void smethod_68(AppDomain appDomain_0, UnhandledExceptionEventHandler unhandledExceptionEventHandler_0)
 {
     appDomain_0.UnhandledException += unhandledExceptionEventHandler_0;
 }
コード例 #33
0
        public void ExceptionInEventHandler(Func <ReadedFileInfo, IChangeable> checkerCreator, string[] workflow)
        {
            string file = Path.GetTempFileName();

            File.WriteAllBytes(file, new byte[] { 1, 2, 3 });
            var fileInfo = ReadedFileInfo.Create(file, _ => _.CopyTo(Stream.Null));

            IChangeable monitor = null;

            var       wait = new ManualResetEvent(false);
            Exception unhandledException           = null;
            UnhandledExceptionEventHandler handler = (sender, args) =>
            {
                unhandledException = (Exception)args.ExceptionObject;
                wait.Set();
            };

            AppDomain.CurrentDomain.UnhandledException += handler;
            try
            {
                foreach (var op in workflow)
                {
                    switch (op)
                    {
                    case "create":
                        monitor = checkerCreator(fileInfo);
                        break;

                    case "subscribe":
                        monitor.Changed += (a, e) =>
                        {
                            throw new Exception("test");
                        };
                        break;

                    case "delete":
                        SafeDelete(file);
                        break;

                    case "modify":
                        Task.Factory.StartNew(() =>
                        {
                            Thread.Sleep(150);
                            using (var fs = new FileStream(file, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
                            {
                                fs.Position = 2;
                                fs.WriteByte(1);
                                fs.Close();
                            };
                        }, TaskCreationOptions.LongRunning);
                        break;

                    case "delay":
                        Thread.Sleep(75);
                        break;

                    default:
                        throw new NotSupportedException();
                    }
                }

                Assert.IsTrue(wait.WaitOne(10000), "10 sec elapsed");
            }
            finally
            {
                AppDomain.CurrentDomain.UnhandledException -= handler;
            }

            Console.WriteLine(unhandledException);

            Assert.That(unhandledException.Message, Is.EqualTo("Error while file checking."));
            Assert.That(unhandledException.InnerException, Is.Not.Null);
            Assert.That(unhandledException.InnerException.Message, Is.EqualTo("test"));
        }
コード例 #34
0
 protected virtual void OnMyEventHandler(UnhandledExceptionEventHandler e)
 {
     var handler = MyEventHandler;
     if (handler != null) handler(this, e);
 }
コード例 #35
0
        private static void Main()
        {
            Class283.Class284 @class = new Class283.Class284();
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            @class.mutex_0                      = null;
            @class.memoryMappedFile_0           = null;
            @class.mutex_1                      = null;
            Thread.CurrentThread.CurrentCulture = (Thread.CurrentThread.CurrentUICulture = Class217.cultureInfo_0);
            Class368 class2 = new Class368(Class291.string_17);

            Class373.Logger = class2;
            Class367 class3 = class2;

            if (Class283.eventHandler_0 == null)
            {
                Class283.eventHandler_0 = new EventHandler <EventArgs25>(Class283.smethod_1);
            }
            class3.LogFileCompressed += Class283.eventHandler_0;
            @class.bool_0             = false;
            @class.action_0           = new Action(@class.method_0);
            @class.bool_1             = false;
            @class.action_1           = new Action(@class.method_1);
            @class.action_2           = new Action(@class.method_2);
            @class.action_3           = new Action <Exception, string>(@class.method_3);
            UnhandledExceptionEventHandler value = new UnhandledExceptionEventHandler(@class.method_4);

            AppDomain.CurrentDomain.UnhandledException += value;
            ThreadExceptionEventHandler value2 = new ThreadExceptionEventHandler(@class.method_5);

            Application.ThreadException += value2;
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            Enum29 @enum = Environment.OSVersion.smethod_0();

            if (@enum > Enum29.const_0 && @enum < Enum29.const_10)
            {
                DialogBox.smethod_3(Class283.string_2, Class283.string_3);
                Application.Exit();
                return;
            }
            try
            {
                try
                {
                    @class.mutex_1 = new Mutex(false, Class283.string_16);
                    if (!(@class.bool_0 = @class.mutex_1.WaitOne()))
                    {
                        Environment.ExitCode = 1;
                        Application.Exit();
                    }
                    else if (Class265.smethod_1(Class283.string_15))
                    {
                        Class283.smethod_0();
                        Environment.ExitCode = 1;
                        Application.Exit();
                    }
                    else if (Class409.Current.Flags.Contains(Class283.string_17))
                    {
                        Environment.ExitCode = 0;
                        Application.Exit();
                    }
                    else if (Class409.Current.Flags.Contains(Class283.string_18))
                    {
                        if (DialogBox.smethod_6(Class283.string_6, Class283.string_7, new Enum39[]
                        {
                            Enum39.const_5,
                            Enum39.const_6
                        }) == DialogResult.Yes)
                        {
                            using (UninstallationCleanUp uninstallationCleanUp = new UninstallationCleanUp())
                            {
                                Application.Run(uninstallationCleanUp);
                            }
                        }
                        Application.Exit();
                    }
                    else
                    {
                        try
                        {
                            @class.mutex_0 = new Mutex(false, Class283.string_15);
                        }
                        catch (Exception ex)
                        {
                            @class.action_1();
                            ex.smethod_0();
                            DialogBox.smethod_4(Class283.string_8, Class283.string_9);
                            Application.Exit();
                            return;
                        }
                        if (!(@class.bool_1 = @class.mutex_0.WaitOne(TimeSpan.Zero, false)))
                        {
                            Class283.smethod_0();
                            Environment.ExitCode = 1;
                            Application.Exit();
                        }
                        else
                        {
                            try
                            {
                                @class.memoryMappedFile_0 = MemoryMappedFile.CreateNew(Class283.string_13, 4L, MemoryMappedFileAccess.ReadWrite);
                            }
                            catch (IOException ex2)
                            {
                                ex2.smethod_0();
                                @class.action_2();
                                if (Marshal.GetHRForException(ex2) == (int)Class265.uint_0)
                                {
                                    Class283.smethod_0();
                                    Environment.ExitCode = 1;
                                    Application.Exit();
                                    return;
                                }
                            }
                            using (Class283.icon_0 = Icon.ExtractAssociatedIcon(Application.ExecutablePath))
                            {
                                Class176 instance = Class176.Instance;
                                DateTime now      = DateTime.Now;
                                if (instance.UpdateStepOn == Enum111.const_6 || (Class110.Instance.ApplicationSettings.UpdateType != Enum78.const_3 && (now - instance.LastCheckedForUpdate).TotalDays >= 14.0))
                                {
                                    bool flag = false;
                                    try
                                    {
                                        using (Updater updater = new Updater(true))
                                        {
                                            Application.Run(updater);
                                            switch (updater.UpdateResult)
                                            {
                                            case Enum43.const_4:
                                            case Enum43.const_6:
                                                flag = true;
                                                break;

                                            case Enum43.const_5:
                                                instance.UpdateStepOn = Enum111.const_0;
                                                flag = true;
                                                Application.Exit();
                                                return;
                                            }
                                        }
                                    }
                                    finally
                                    {
                                        if (flag)
                                        {
                                            instance.LastCheckedForUpdate = now;
                                            instance.method_0();
                                        }
                                    }
                                }
                                try
                                {
                                    using (Class435 class4 = new Class435())
                                    {
                                        EventHandler <EventArgs11> eventHandler = null;
                                        Class283.Class285          class5       = new Class283.Class285();
                                        class5.class284_0 = @class;
                                        class5.class330_0 = new Class330();
                                        try
                                        {
                                            Class435 class6 = class4;
                                            if (eventHandler == null)
                                            {
                                                eventHandler = new EventHandler <EventArgs11>(class5.method_0);
                                            }
                                            class6.DataReceived += eventHandler;
                                            if (@class.memoryMappedFile_0 != null)
                                            {
                                                using (MemoryMappedViewStream memoryMappedViewStream = @class.memoryMappedFile_0.CreateViewStream(0L, (long)Class283.int_0, MemoryMappedFileAccess.ReadWrite))
                                                {
                                                    using (BinaryWriter binaryWriter = new BinaryWriter(memoryMappedViewStream, Class217.encoding_0))
                                                    {
                                                        binaryWriter.Write(Process.GetCurrentProcess().Id);
                                                        binaryWriter.Write(class4.Handle.ToInt64());
                                                    }
                                                }
                                            }
                                            @class.action_0();
                                            bool flag2 = Class409.Current.Flags.Contains("DEBUG");
                                            try
                                            {
                                                if (flag2)
                                                {
                                                    Class335.smethod_0(Class291.DebugLogDirectory);
                                                    Class110.Instance.CreatedFileArchive.method_4(Class335.LogFile);
                                                    Class335.smethod_2(Class283.string_5, false);
                                                    Class335.smethod_2(Class283.string_4, false);
                                                }
                                                Application.Run(class5.class330_0);
                                            }
                                            finally
                                            {
                                                if (flag2)
                                                {
                                                    Class335.smethod_2(Class283.string_5, false);
                                                    Class335.smethod_1();
                                                }
                                            }
                                        }
                                        finally
                                        {
                                            if (class5.class330_0 != null)
                                            {
                                                ((IDisposable)class5.class330_0).Dispose();
                                            }
                                        }
                                    }
                                }
                                finally
                                {
                                    Class110.smethod_1();
                                }
                            }
                        }
                    }
                }
                finally
                {
                    @class.action_0();
                }
            }
            finally
            {
                @class.action_1();
                @class.action_2();
                Application.ThreadException -= value2;
            }
        }
コード例 #36
0
 private void SetupErrorHandle()
 {
     exceptionHandler = new UnhandledExceptionEventHandler(CurrentDomainOnUnhandledException);
     AppDomain.CurrentDomain.UnhandledException += exceptionHandler;
 }
コード例 #37
0
 public TestExceptionHandler(UnhandledExceptionEventHandler handler)
 {
     this.handler = handler;
     AppDomain.CurrentDomain.UnhandledException += handler;
 }
コード例 #38
0
ファイル: ConsoleHost.cs プロジェクト: nickchal/pash
		internal ConsoleHost(RunspaceConfiguration configuration)
		{
			this.savedWindowTitle = "";
			this.id = Guid.NewGuid();
			this.ver = PSVersionInfo.PSVersion;
			this.noExit = true;
			this.hostGlobalLock = new object();
			this.transcriptFileName = string.Empty;
			this.transcriptionStateLock = new object();
			Thread.CurrentThread.CurrentUICulture = this.CurrentUICulture;
			Thread.CurrentThread.CurrentCulture = this.CurrentCulture;
			base.ShouldSetThreadUILanguageToZero = true;
			this.debuggerCommandProcessor = new HostUtilities.DebuggerCommandProcessor();
			this.inDebugMode = false;
			this.displayDebuggerBanner = true;
			this.configuration = configuration;
			this.ui = new ConsoleHostUserInterface(this);
			this.consoleWriter = new ConsoleTextWriter(this.ui);
			ConsoleHost.exitOnCtrlBreakMessage = ConsoleHostStrings.ExitOnCtrlBreakMessage;
			UnhandledExceptionEventHandler unhandledExceptionEventHandler = new UnhandledExceptionEventHandler(this.UnhandledExceptionHandler);
			AppDomain.CurrentDomain.UnhandledException += unhandledExceptionEventHandler;
		}
コード例 #39
0
ファイル: Class1.cs プロジェクト: pilotdes/Traffic-Warden
 public static void InitReporting()
 {
     handler =
     new UnhandledExceptionEventHandler(Target)
 }
コード例 #40
0
 public UnhandledExceptionHelperWin(UnhandledExceptionEventHandler handler, bool addExceptionHandling = true) : this(addExceptionHandling)
 {
     if (handler != null) UnhandledException += handler;
 }
コード例 #41
0
 public void SetUnhandledExceptionHandler(UnhandledExceptionEventHandler handler)
 {
     exceptionHandler = handler;
 }
コード例 #42
0
ファイル: TaskExceptionHandler.cs プロジェクト: CriDos/AsTask
 public static void AddUnhandledException(UnhandledExceptionEventHandler exceptionHandler)
 {
     AppDomain.CurrentDomain.UnhandledException += exceptionHandler;
 }
コード例 #43
0
        private void Initialize(bool exitOnUnhandledException, bool threadExceptionHandlerActivated, UnhandledExceptionEventHandler handlerFunction)
        {
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            if (threadExceptionHandlerActivated)
            {
                Application.ThreadException += ThreadExceptionHandler;
            }

            this.exitOnUnhandledException = exitOnUnhandledException;

            var currentDomain = AppDomain.CurrentDomain;

            currentDomain.UnhandledException += handlerFunction;
        }
コード例 #44
0
        public static void UnregisterAppDomainUnhandledExceptionHandler(this ExceptionlessClient client) {
            if (client == null)
                throw new ArgumentNullException(nameof(client));

            if (_onAppDomainUnhandledException == null)
                return;
            
            AppDomain.CurrentDomain.UnhandledException -= _onAppDomainUnhandledException;
            _onAppDomainUnhandledException = null;
        }
コード例 #45
0
        /// <summary>A thread worker function that processes items from the work queue.</summary>
        private static void ProcessQueuedItems()
        {
            // Process indefinitely
            while (true)
            {
                //判断有无资源操作,如果有则执行【即从队列中取】,如没有则将当前线程置为等待。注意当前信息量中count数量与_waitingCallbacks队列长度相同。
                //通过QueueUserWorkItem的_workerThreadNeeded.AddOne();代码行来告之在当前线程池中处于wait的线程列表中找出一个线程来执行_waitingCallbacks列队中的任务(Dequeue).
                //如果进程池中所有线程均为执行状态时,则系统还运行QueueUserWorkItem()函数则可视其仅将任务放入队列即可,因为此处的while(true)会不断从队列中获取任务执行。
                _workerThreadNeeded.WaitOne();

                // Get the next item in the queue.  If there is nothing there, go to sleep
                // for a while until we're woken up when a callback is waiting.
                WaitingCallback callback = null;

                // Try to get the next callback available.  We need to lock on the
                // queue in order to make our count check and retrieval atomic.
                lock (_poolLock)
                {
                    if (_waitingCallbacks.Count > 0)
                    {
                        try { callback = (WaitingCallback)_waitingCallbacks.Dequeue(); }
                        catch { } // make sure not to fail here
                    }
                }

                if (callback != null)
                {
                    // We now have a callback.  Execute it.  Make sure to accurately
                    // record how many callbacks are currently executing.
                    try
                    {
                        Interlocked.Increment(ref _inUseThreads);
                        callback.Callback(callback.State);
                    }
#if NET1
                    catch (Exception exc)
                    {
                        //暂时注释下面的代码
                        try
                        {
                            UnhandledExceptionEventHandler handler = UnhandledException;
                            if (handler != null)
                            {
                                handler(typeof(ManagedThreadPool), new UnhandledExceptionEventArgs(exc, false));
                            }
                        }
                        catch {}
                    }
#else
                    catch
                    {
                        ;
                    }
#endif

                    finally
                    {
                        Interlocked.Decrement(ref _inUseThreads);
                    }
                }
            }
        }
コード例 #46
0
ファイル: Server.cs プロジェクト: CuneytKukrer/TestProject
 private void StartQuery(QueryRunner runner)
 {
     object obj2;
     lock ((obj2 = this._statusLocker))
     {
         if (this._cancelRequest)
         {
             return;
         }
     }
     _currentServer = this;
     this.ServerThread = Thread.CurrentThread;
     if ((this._repository != null) && this._repository.DriverLoader.IsValid)
     {
         this._dataContextDriver = this._repository.DriverLoader.Driver;
     }
     if ((this._dataContextDriver is EntityFrameworkDriver) || (this._dataContextDriver is EntityFrameworkDbContextDriver))
     {
         this.InstallDbProviders(this._repository);
     }
     lock ((obj2 = this._statusLocker))
     {
         if (this._cancelRequest)
         {
             return;
         }
     }
     if (_domainExceptionHandler != null)
     {
         System.AppDomain.CurrentDomain.UnhandledException -= _domainExceptionHandler;
     }
     System.AppDomain.CurrentDomain.UnhandledException += (_domainExceptionHandler = new UnhandledExceptionEventHandler(this.CurrentDomain_UnhandledException));
     try
     {
         this.RunQuery(runner);
     }
     catch (ThreadAbortException)
     {
     }
     catch (Exception exception)
     {
         this.MessageLoopEnded = true;
         this.PostStatus(this.GetStatusArgs(exception, true, true));
         this.PerformCompletionCleanup(true, false);
         this.PerformFinalCleanup();
     }
 }
コード例 #47
0
        /// <summary>
        /// Загрузить плюгИн с указанным наименованием
        /// </summary>
        /// <param name="name">Наименование плюгИна</param>
#if _SEPARATE_APPDOMAIN
        /// <param name="delegateSeparateAppDomain_UnhandledException">Обработчик необработанных секциями try/catch исключений</param>
#endif
        /// <param name="iRes">Результат загрузки (код ошибки)</param>
        /// <returns>Загруженный плюгИн</returns>
        protected PlugInBase load(string name
#if _SEPARATE_APPDOMAIN
                                  , UnhandledExceptionEventHandler delegateSeparateAppDomain_UnhandledException
#endif
                                  , out int iRes)
        {
            PlugInBase plugInRes = null;
            Assembly   ass       = null;

            iRes = -1;

            Type objType = null;

            try {
#if _SEPARATE_APPDOMAIN
                if (isInitPluginAppDomain == false)
                {
                    initPluginDomain(name, delegateSeparateAppDomain_UnhandledException);
                }
                else
                {
                    ;
                }
#endif
                ass =
#if _SEPARATE_APPDOMAIN
                    m_proxyAppDomain.GetAssembly
#else
                    Assembly.LoadFrom
#endif
                        (Environment.CurrentDirectory + @"\" + name + @".dll");

                if (!(ass == null))
                {
                    objType = ass.GetType(name + ".PlugIn");
                }
                else
                {
                    ;
                }
            } catch (Exception e) {
                Logging.Logg().Exception(e, @"FormMain::loadPlugin () ... LoadFrom () ... plugIn.Name = " + name, Logging.INDEX_MESSAGE.NOT_SET);
            }

            if (!(objType == null))
            {
                try {
                    plugInRes      = ((PlugInBase)Activator.CreateInstance(objType));
                    plugInRes.Host = (IPlugInHost)this; //Вызов 'Register'

                    iRes = 0;
                } catch (Exception e) {
                    iRes = -2;

                    Logging.Logg().Exception(e, @"FormMain::loadPlugin () ... CreateInstance ... plugIn.Name = " + name, Logging.INDEX_MESSAGE.NOT_SET);
                }
            }
            else
            {
                Logging.Logg().Error(@"FormMain::loadPlugin () ... Assembly.GetType()=null ... plugIn.Name = " + name, Logging.INDEX_MESSAGE.NOT_SET);
            }

            return(plugInRes);
        }
コード例 #48
0
        protected virtual void onBootstrap()
        {
            var s = this.mainShell;

            if (s == null)
            {
                return;
            }

            var m = this.newMessenger?.Invoke();

            if (m != null)
            {
                m.Subscriber = s;
            }

            var e = this.executor;

            e?.Execute(new SetupMethodWebCommand(
                           new MethodWebV2(),
                           m,
                           this.newConfigSaver,
                           this.newSettingsProvider));

            var w = e?.Get <SetupMethodWebCommand>()?.W;

            w?.Run <EventSubscriber>(sub =>
            {
                var cd = AppDomain.CurrentDomain;
                UnhandledExceptionEventHandler handler = this.handleException;
                sub.Subscribe(
                    cd,
                    nameof(cd.UnhandledException),
                    handler);
            });
            w?.RegisterDependency(s);

            HomeUi          homeUi       = null;
            HomeNavUi       homeNavUi    = null;
            StatisticsUi    statsUi      = null;
            TimestampsUi    timestampsUi = null;
            TimestampEditUi editUi       = null;
            DailyUi         dailyUi      = null;
            ConfigUi        configUi     = null;
            LicenseUi       licenseUi    = null;

            w?.Run <UiReaderWriter, Lotter>(
                (uiRW, lotter) =>
            {
                uiRW.WriteSync(
                    s,
                    () =>
                {
                    homeUi       = this.newHomeUi?.Invoke();
                    homeNavUi    = this.newHomeNavUi?.Invoke(lotter);
                    statsUi      = this.newStatsUi?.Invoke();
                    timestampsUi = this.newTimestampsUi?.Invoke(lotter);
                    editUi       = this.newEditUi?.Invoke();
                    dailyUi      = this.newDailyUi?.Invoke(lotter);
                    configUi     = this.newConfigUi?.Invoke();
                    licenseUi    = this.newLicenseUi?.Invoke(s);
                });
            });

            var homeFinished       = new ManualResetEvent(false);
            var homeNavFinished    = new ManualResetEvent(false);
            var statsFinished      = new ManualResetEvent(false);
            var editFinished       = new ManualResetEvent(false);
            var timestampsFinished = new ManualResetEvent(false);
            var dailyFinished      = new ManualResetEvent(false);
            var mainFinished       = new ManualResetEvent(false);
            var shutdownFinished   = new ManualResetEvent(false);
            var licenseFinished    = new ManualResetEvent(false);
            var configFinished     = new ManualResetEvent(false);

            w?.Run <Do <Do> >(invoker =>
            {
                invoker.Invoke(
                    () =>
                {
                    e?.Execute(
                        new SetupHomeCommand(
                            homeUi,
                            s,
                            this.newReaderWriter,
                            this.newDataWatcher,
                            w));
                    homeFinished.Set();
                });

                invoker.Invoke(
                    () =>
                {
                    e?.Execute(
                        new SetupHomeNavCommand(
                            homeNavUi,
                            s.NavUi,
                            new NavigatorNavLogicReader(w),
                            w));
                    homeNavFinished.Set();
                });

                invoker.Invoke(
                    () =>
                {
                    e?.Execute(
                        new SetupStatisticsCommand(
                            statsUi,
                            homeUi,
                            w));
                    statsFinished.Set();
                });

                invoker.Invoke(
                    () =>
                {
                    e?.Execute(
                        new SetupTimestampEditCommand(
                            editUi,
                            homeUi,
                            w));
                    editFinished.Set();
                });

                invoker.Invoke(
                    () =>
                {
                    e?.Execute(
                        new SetupMainCommand(
                            s,
                            w,
                            new SettingsHolder()));
                    mainFinished.Set();
                });

                invoker.Invoke(
                    () =>
                {
                    e?.Execute(
                        new SetupShutdownCommand(
                            w));
                    shutdownFinished.Set();
                });

                invoker.Invoke(
                    () =>
                {
                    e?.Execute(
                        new SetupLicenseCommand(
                            licenseUi,
                            w));
                    licenseFinished.Set();
                });

                homeFinished.WaitOne();

                invoker.Invoke(
                    () =>
                {
                    e?.Execute(
                        new SetupTimestampsCommand(
                            timestampsUi,
                            homeUi,
                            w));
                    timestampsFinished.Set();
                });

                invoker.Invoke(
                    () =>
                {
                    e?.Execute(
                        new SetupDailyCommand(
                            dailyUi,
                            homeUi,
                            new NavigatorUiReader(w),
                            w));
                    dailyFinished.Set();
                });
            });

            // update to single-file format
            w?.Run <FileTimestampManager>(manager =>
            {
                manager.ConvertToSingleFile();
            });

            w?.Run <DataWatcher>(watcher =>
            {
                watcher.Start();
            });

            w?.Run <Navigator>(
                nav =>
            {
                nav.Present <HomePresenter>();

                w.Run <Do <Do> >(invoker =>
                {
                    homeNavFinished.WaitOne();
                });

                nav.PresentFluidly <HomeNavPresenter>();

                w.Run <Do <Do> >(invoker =>
                {
                    timestampsFinished.WaitOne();
                });

                nav.PresentFluidly <TimestampsPresenter>();
            });

            w?.Run <Do <Do> >(invoker =>
            {
                dailyFinished.WaitOne();
                invoker.Invoke(() =>
                {
                    e?.Execute(
                        new SetupConfigCommand(
                            configUi,
                            homeUi,
                            w));
                    configFinished.Set();
                });

                statsFinished.WaitOne();
                editFinished.WaitOne();
                mainFinished.WaitOne();
                shutdownFinished.WaitOne();
                licenseFinished.WaitOne();
                configFinished.WaitOne();
            });
        }
コード例 #49
0
 private void HandleApplicationError(object sender, UnhandledExceptionEventHandler unhandledException)
 {
     unhandledException(sender, new UnhandledExceptionEventArgs(new Exception(), true));
 }
コード例 #50
0
ファイル: MemoryCache.cs プロジェクト: Numpsy/mono
 private void InitDisposableMembers(NameValueCollection config) {
     bool dispose = true;
     try {
         try {
             _perfCounters = new PerfCounters(_name);
         }
         catch {
             // ignore exceptions from perf counters
         }
         for (int i = 0; i < _stores.Length; i++) {
             _stores[i] = new MemoryCacheStore(this, _perfCounters);
         }
         _stats = new MemoryCacheStatistics(this, config);
         AppDomain appDomain = Thread.GetDomain();
         EventHandler onAppDomainUnload = new EventHandler(OnAppDomainUnload);
         appDomain.DomainUnload += onAppDomainUnload;
         _onAppDomainUnload = onAppDomainUnload;
         UnhandledExceptionEventHandler onUnhandledException = new UnhandledExceptionEventHandler(OnUnhandledException);
         appDomain.UnhandledException += onUnhandledException;
         _onUnhandledException = onUnhandledException;
         dispose = false;
     }
     finally {
         if (dispose) {
             Dispose();
         }
     }
 }
コード例 #51
0
 /// <summary>
 /// The main entry point for the application.
 /// </summary>
 public int ServiceMain(UnhandledExceptionEventHandler handler, params string[] parameters)
 {
     return(Run(handler, parameters));
 }
コード例 #52
0
		public TestExceptionHandler( UnhandledExceptionEventHandler handler )
		{
			this.handler = handler;
			AppDomain.CurrentDomain.UnhandledException += handler;
		}
コード例 #53
0
        /// <summary>
        /// See [XRLoader.DeInitialize](xref:UnityEngine.XR.Management.XRLoader.Stop)
        /// </summary>
        /// <returns>True if deinitialized, false otherwise.</returns>
        public override bool Deinitialize()
        {
            if (currentLoaderState == LoaderState.Uninitialized)
            {
                return(true);
            }

            if (!validLoaderDeinitStates.Contains(currentLoaderState))
            {
                return(false);
            }

            currentLoaderState = LoaderState.DeinitializeAttempted;

            try
            {
#if TEST_SUPPORT
                if (ShouldExitEarly())
                {
                    return(false);
                }

                // The test hook above will leave the loader in a half initialized state.  To work
                // around this we reset the instance pointer if it is missing.
                if (Instance == null)
                {
                    Instance = this;
                }
#endif
                Application.onBeforeRender -= ProcessOpenXRMessageLoop;

                ProcessOpenXRMessageLoop(); // Drain any remaining events.

                OpenXRFeature.ReceiveLoaderEvent(this, OpenXRFeature.LoaderEvent.SubsystemDestroy);

                DestroySubsystem <XRInputSubsystem>();
                DestroySubsystem <XRDisplaySubsystem>();

                DiagnosticReport.DumpReport("System Shutdown");

                Internal_DestroySession();

                ProcessOpenXRMessageLoop();

                Internal_UnloadOpenXRLibrary();

                currentLoaderState = LoaderState.Uninitialized;

                if (unhandledExceptionHandler != null)
                {
                    AppDomain currentDomain = AppDomain.CurrentDomain;
                    currentDomain.UnhandledException -= unhandledExceptionHandler;
                    unhandledExceptionHandler         = null;
                }

                return(base.Deinitialize());
            }
            finally
            {
                // Ensure we always clear the instance reference even if some part of Deinitialize threw an exception
                Instance = null;
            }
        }
コード例 #54
0
ファイル: ConsoleHost.cs プロジェクト: dfinke/powershell
        /// <summary>
        /// 
        /// Constructs a new instance
        /// 
        /// </summary>
        internal ConsoleHost(RunspaceConfiguration configuration)
        {
            ClrFacade.SetCurrentThreadUiCulture(this.CurrentUICulture);
            ClrFacade.SetCurrentThreadCulture(this.CurrentCulture);
            // BUG: 610329. Tell PowerShell engine to apply console
            // related properties while launching Pipeline Execution
            // Thread.
            base.ShouldSetThreadUILanguageToZero = true;

            InDebugMode = false;
            _displayDebuggerBanner = true;

            _configuration = configuration;
            this.ui = new ConsoleHostUserInterface(this);
            _consoleWriter = new ConsoleTextWriter(ui);

#if !CORECLR // CurrentDomain.UnhandledException not supported on CoreCLR
            UnhandledExceptionEventHandler handler = new UnhandledExceptionEventHandler(UnhandledExceptionHandler);
            AppDomain.CurrentDomain.UnhandledException += handler;
#endif
        }
コード例 #55
0
 /// <summary>
 /// Adds an handler for rendering exceptions.
 /// </summary>
 public static IElectronHost UseExceptionHandler(this IElectronHost host, UnhandledExceptionEventHandler handler)
 {
     host.UnhandledException += handler;
     return(host);
 }