static int Main(string[] doNotUse) { // RegFree COM is not supported on Windows Nano if (TestLibrary.Utilities.IsWindowsNanoServer) { return(100); } try { RunTests(); Console.WriteLine("Testing COM object lifetime control methods."); Thread.CurrentThread.DisableComObjectEagerCleanup(); RunTests(); Marshal.CleanupUnusedObjectsInCurrentContext(); Assert.IsFalse(Marshal.AreComObjectsAvailableForCleanup()); } catch (Exception e) { Console.WriteLine($"Test Failure: {e}"); return(101); } return(100); }
public static void MiscellaneousTest() { Thread.BeginCriticalRegion(); Thread.EndCriticalRegion(); Thread.BeginThreadAffinity(); Thread.EndThreadAffinity(); ThreadTestHelpers.RunTestInBackgroundThread(() => { // TODO: Port tests for these once all of the necessary interop APIs are available Thread.CurrentThread.DisableComObjectEagerCleanup(); Marshal.CleanupUnusedObjectsInCurrentContext(); }); #pragma warning disable 618 // obsolete members Assert.Throws <InvalidOperationException>(() => Thread.CurrentThread.GetCompressedStack()); Assert.Throws <InvalidOperationException>(() => Thread.CurrentThread.SetCompressedStack(CompressedStack.Capture())); #pragma warning restore 618 // obsolete members Thread.MemoryBarrier(); var ad = Thread.GetDomain(); Assert.NotNull(ad); Assert.Equal(AppDomain.CurrentDomain, ad); Assert.Equal(ad.Id, Thread.GetDomainID()); Thread.SpinWait(int.MinValue); Thread.SpinWait(-1); Thread.SpinWait(0); Thread.SpinWait(1); Thread.Yield(); }
static void TestCameraStartStop() { int i = 0; var collections = new FilterInfoCollection(FilterCategory.VideoInputDevice); var _capture = new VideoCaptureDevice(collections[i].MonikerString); _capture.VideoResolution = _capture.VideoCapabilities.FirstOrDefault(item => System.Math.Abs(item.FrameSize.Width - 320) < 0.1 && System.Math.Abs(item.FrameSize.Height - 240) < 0.1); _capture.NewFrame += _captures_NewFrame; int steps = 300 * 30 * 3; do { _capture.Start(); Thread.Sleep(100); _capture.SignalToStop(); _capture.WaitForStop(); i++; Marshal.CleanupUnusedObjectsInCurrentContext(); GC.WaitForFullGCComplete(); GC.GetTotalMemory(true); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); string str = string.Format("Test nr {0}/{1}, mem = {2} Mbytes", i, steps, Process.GetCurrentProcess().PrivateMemorySize64 / 1024.0 / 1024.0); Console.WriteLine(str); } while (i < steps); Console.ReadKey(); }
public async Task DoForceGCAsync() { if (IsMeasuringCurrentProcess) { const int MAX_CLEANUP_CYCLES = 10; // Each time a GC occurs more COM objects can become available for cleanup. // So we keep calling until no more objects are available for cleanup OR // we reach a hard coded limit. for (int iLoopCount = 0; iLoopCount < MAX_CLEANUP_CYCLES; ++iLoopCount) { GC.Collect(GC.MaxGeneration); GC.WaitForPendingFinalizers(); if (!Marshal.AreComObjectsAvailableForCleanup()) { break; } Marshal.CleanupUnusedObjectsInCurrentContext(); } } else { // we just finished executing the user code. The IDE might be busy executing the last request. // we need to delay some or else System.Runtime.InteropServices.COMException (0x8001010A): The message filter indicated that the application is busy. (Exception from HRESULT: 0x8001010A (RPC_E_SERVERCALL_RETRYLATER)) //await Task.Delay(TimeSpan.FromSeconds(1 * stressUtilOptions.DelayMultiplier)).ConfigureAwait(false); // cmdidShellForceGC GarbageCollectCLRIterative https://devdiv.visualstudio.com/DevDiv/_git/VS?path=%2Fsrc%2Fappid%2FAppDomainManager%2FVsRcwCleanup.cs&version=GBmaster&_a=contents await stressUtilOptions.VSHandler.DteExecuteCommand("Tools.ForceGC"); //await Task.Delay(TimeSpan.FromSeconds(1 * stressUtilOptions.DelayMultiplier)).ConfigureAwait(false); } }
public static void Run(string targetDirectory, Boolean watchDirectory) { if (!Directory.Exists(targetDirectory)) { Console.WriteLine("Directory does not exist. Either modify the configuration file, or run this program again and re-save the configuration. Press any key to exit."); Console.ReadLine(); return; } Logger logger = new Logger(Path.Combine(targetDirectory, String.Format("_log-{0}.txt", ExtractFootnotes.Timestamp))); CleanUpWordInstances(logger); var previousConversionTextFiles = Directory.EnumerateFiles(targetDirectory, "*.txt").Where(f => !f.Contains("_log")); if (previousConversionTextFiles.Count() > 0) { logger.log("Cleanup conversion text files", true); foreach (string textFile in previousConversionTextFiles) { File.Delete(textFile); } } var previousConversionWordTemporaryFiles = Directory.EnumerateFiles(targetDirectory, "*.docx").Where(f => f.Contains("~$o_")); if (previousConversionWordTemporaryFiles.Count() > 0) { logger.log("Cleanup conversion Word temporary files", true); foreach (string wordFile in previousConversionWordTemporaryFiles) { File.Delete(wordFile); } } logger.log("Start", true); var files = Directory.EnumerateFiles(targetDirectory, "*.docx").Where(f => !f.Contains("~$o_")); logger.log(String.Format("The number of files is {0}.", files.Count()), true); Parallel.ForEach(files, new ParallelOptions { MaxDegreeOfParallelism = 3 }, file => { ProcessFile(file, logger); }); Marshal.CleanupUnusedObjectsInCurrentContext(); CleanUpWordInstances(logger); logger.log("Finish", true); }
public void CleanupUnusedObjectsInCurrentContext_InvokeSeveralTimes_Success() { Marshal.CleanupUnusedObjectsInCurrentContext(); Assert.False(Marshal.AreComObjectsAvailableForCleanup()); // Invoke twice to make sure things work when unused objects have already been // cleaned up and there is nothing to do. Marshal.CleanupUnusedObjectsInCurrentContext(); Assert.False(Marshal.AreComObjectsAvailableForCleanup()); }
private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { //isCancellationRequested = true; if (Marshal.AreComObjectsAvailableForCleanup()) { Marshal.CleanupUnusedObjectsInCurrentContext(); } GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); }
private void OnAggregatedObjectCreated() { // The VS main thread disables eager COM object cleanup, which means that // COM objects are only cleaned up when Marshal.CleanupUnusedObjectsInCurrentContext // is called. The shell normally does this on idle, but in long lived // code model operations, we end up creating enough code model objects that // we can run out of memory before an idle+gc actually happens. // // To work around this, we track when we create aggregated objects (currently only) // really used for the codemodel RCW's, and call // Marshal.CleanupUnusedObjectsInCurrentContext periodically. This is safe because // we're only cleaning things up for a given context, which means that there is no // need to pump to get to the right context, so it shouldn't cause unexpected // re-entrancy issues. // // The "1000" is completely arbitrary, except that it seems to work well when looking at // http://vstfdevdiv:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=711863 if (_aggregatedObjectsCreatedSinceLastCleanup++ == 1000) { Marshal.CleanupUnusedObjectsInCurrentContext(); _aggregatedObjectsCreatedSinceLastCleanup = 0; } }
private void FastFinder_FormClosing(object sender, FormClosingEventArgs e) { Marshal.CleanupUnusedObjectsInCurrentContext(); n.Visible = false; }
public AreaFillArea(AreaFillWindow areaFillWindow, IntPtr bgdOcean) : base(bgdOcean) { _iAreaFill = new Lazy <IAreaFill>(() => { var guidComClass = new Guid("BB4B9EE1-81DE-400B-A58A-687ED53A02E6"); var hr = CoCreateFromFile("CppLib.dll", guidComClass, typeof(IAreaFill).GUID, out var pObject); var iAreaFill = (IAreaFill)Marshal.GetTypedObjectForIUnknown(pObject, typeof(IAreaFill)); return(iAreaFill); }); this.Loaded += (ol, el) => { Window.GetWindow(this).Closed += (oc, ec) => { if (_iAreaFill.IsValueCreated) { if (IsRunning) { IsRunning = false; } Marshal.ReleaseComObject(_iAreaFill.Value); GC.Collect(); Marshal.CleanupUnusedObjectsInCurrentContext(); FreeLibrary(_hModule); } }; }; LstWndProcMsgs.Add((int)NativeMethods.WM_.WM_NCHITTEST); LstWndProcMsgs.Add((int)NativeMethods.WM_.WM_MOUSEMOVE); LstWndProcMsgs.Add((int)NativeMethods.WM_.WM_LBUTTONDOWN); LstWndProcMsgs.Add((int)NativeMethods.WM_.WM_RBUTTONUP); this._areaFillWindow = areaFillWindow; this._bgdOcean = bgdOcean; this.WndProcExt = (int msg, IntPtr wParam, IntPtr lParam, ref bool handled) => { switch ((NativeMethods.WM_)msg) { case NativeMethods.WM_.WM_NCHITTEST: handled = true; return(new IntPtr(1)); // HTCLIENT case NativeMethods.WM_.WM_LBUTTONDOWN: case NativeMethods.WM_.WM_LBUTTONUP: case NativeMethods.WM_.WM_MOUSEMOVE: case NativeMethods.WM_.WM_RBUTTONUP: var x = lParam.ToInt32() & 0xffff; var y = (lParam.ToInt32() >> 16) & 0xffff; var pt = new Point(x, y); //var arg = new MouseEventArgs(Mouse.PrimaryDevice, 0); //arg.RoutedEvent = Mouse.MouseMoveEvent; switch ((NativeMethods.WM_)msg) { case NativeMethods.WM_.WM_MOUSEMOVE: this.MyOnMouseMove(pt, wParam); break; case NativeMethods.WM_.WM_LBUTTONDOWN: this.MyOnOnMouseDown(pt, wParam); break; case NativeMethods.WM_.WM_LBUTTONUP: case NativeMethods.WM_.WM_RBUTTONUP: this.MyOnOnMouseUp(pt, wParam, msg); break; } break; } return(IntPtr.Zero); }; }
public async Task DoitAsync() { await SendTelemetryAsync($"{nameof(DumperViewerMain)}"); _logger.LogMessage($"in {nameof(DumperViewerMain)} LoggerObj={_logger} args = '{string.Join(" ", args)}'"); if (args.Length == 0) { _procTarget = ChooseProcess("Choose a process to dump/analyze", fShow32BitOnly: true); _StartClrObjExplorer = true; if (_procTarget == null) { DoShowHelp(); return; } } else { int iArg = 0; var argsGood = true; var extraErrInfo = string.Empty; try { while (iArg < args.Length) { var curArg = args[iArg++].Trim(); if (curArg.Length > 1 && "-/".IndexOf(curArg[0]) == 0) { switch (curArg[1].ToString().ToLower()) { case "?": DoShowHelp(); return; case "p": if (iArg == args.Length) { throw new ArgumentException("Expected process id"); } var pid = int.Parse(args[iArg++]); _procTarget = Process.GetProcessById(pid); break; case "r": if (iArg == args.Length) { throw new ArgumentException("Expected regex"); } var splitRegExes = args[iArg++].Split(new[] { '|' }); foreach (var split in splitRegExes) { this.regexes.Add(split); } break; case "c": // start ClrObjExplorer this._StartClrObjExplorer = true; break; case "f": if (iArg == args.Length) { throw new ArgumentException("dump filename"); } this._DumpFileName = args[iArg++]; if (this._DumpFileName.StartsWith("\"") && this._DumpFileName.EndsWith("\"")) { this._DumpFileName = this._DumpFileName.Replace("\"", string.Empty); } this._DumpFileName = Path.ChangeExtension(this._DumpFileName, "dmp"); if (File.Exists(this._DumpFileName)) { throw new InvalidOperationException($"{this._DumpFileName} already exists. Aborting"); } break; case "d": break; } } else { _logger.LogMessage($"Invalid arguments"); argsGood = false; } } } catch (Exception ex) { argsGood = false; extraErrInfo = ex.ToString(); } if (!argsGood) { DoShowHelp(extraErrInfo); return; } } try { var sw = Stopwatch.StartNew(); if (string.IsNullOrEmpty(_DumpFileName)) { throw new InvalidOperationException("Must specify dump filename"); } await Task.Run(() => { var mdh = new MemoryDumpHelper(); _logger.LogMessage($"Starting to create dump {_procTarget.Id} {_procTarget.ProcessName} {_DumpFileName}"); if (_procTarget.Id == Process.GetCurrentProcess().Id) { for (int i = 0; i < 5; i++) { GC.Collect(); GC.WaitForPendingFinalizers(); Marshal.CleanupUnusedObjectsInCurrentContext(); } } mdh.CollectDump(process: _procTarget, dumpFilePath: _DumpFileName, fIncludeFullHeap: true); }); _logger.LogMessage($"Done creating dump {_procTarget.Id} {_procTarget.ProcessName} {new FileInfo(_DumpFileName).Length:n0} Secs={sw.Elapsed.TotalSeconds:f3}"); if (_StartClrObjExplorer) { sw.Restart(); await Task.Run(() => { LogMessage($"Loading dump in DumpAnalyzer {_DumpFileName}"); var oAnalyzer = new DumpAnalyzer(_logger); _logger.LogMessage($@"Start ClrObjExplorer: ""{oAnalyzer.GetClrObjExplorerPath()}"" ""{_DumpFileName}"""); oAnalyzer.StartClrObjExplorer(_DumpFileName); }); _logger.LogMessage($"Done Analyzing dump {_procTarget.Id} {_procTarget.ProcessName} Secs={sw.Elapsed.TotalSeconds:f3}"); } else { var oAnalyzer = new DumpAnalyzer(_logger); LogMessage($@"To start ClrObjExplorer:""{oAnalyzer.GetClrObjExplorerPath()}"" ""{_DumpFileName}"""); } } catch (Exception ex) { _logger.LogMessage($"exception creating dump {ex}"); } }