System.GC.WaitForPendingFinalizers()

Here are the examples of the csharp api System.GC.WaitForPendingFinalizers() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

519 Examples 7

19 Source : Epd7In5BcTests.cs
with MIT License
from eXoCooLd

[Test]
        public void FinalizerNoHardwareTest()
        {
            var result = new Epd7In5Bc();

            replacedert.NotNull(result, "Object should not be null");

            // ReSharper disable once Redundantreplacedignment
#pragma warning disable IDE0059 // Unnecessary replacedignment of a value
            result = null;
#pragma warning restore IDE0059 // Unnecessary replacedignment of a value

            GC.Collect();
            GC.WaitForPendingFinalizers();
        }

19 Source : Host.cs
with MIT License
from FabianTerhorst

[MethodImpl(MethodImplOptions.NoInlining)]
        public static int ExecuteResourceUnload(IntPtr arg, int argLength)
        {
            if (argLength < Marshal.SizeOf(typeof(UnloadArgs)))
            {
                return 1;
            }

            var libArgs = Marshal.PtrToStructure<UnloadArgs>(arg);
            var resourcePath = Marshal.PtrToStringUTF8(libArgs.ResourcePath);
            var resourceMain = Marshal.PtrToStringUTF8(libArgs.ResourceMain);
            var resourceDllPath = GetPath(resourcePath, resourceMain);
            var weakLoadContext = UnloadreplacedemblyLoadContext(resourcePath, resourceDllPath);
            if (weakLoadContext == null) return 1;
            for (var i = 0; i < 8 && weakLoadContext.IsAlive; i++)
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }

            if (weakLoadContext.IsAlive)
            {
                Console.WriteLine("Resource " + resourcePath + " memory leaked!");
            }

            return 0;
        }

19 Source : EventInfoTests.cs
with MIT License
from Faithlife

[Test]
		public void WeakSubscribeCollectedTest()
		{
			var eventSource = new EventSource();

			CreateEventTarget(eventSource);

			GC.Collect();
			GC.WaitForPendingFinalizers();
			GC.Collect();

			replacedert.AreEqual(3, EventTarget.RaiseCount);
			eventSource.RaiseEvents();
			replacedert.AreEqual(3, EventTarget.RaiseCount);
		}

19 Source : MutationTestProject.cs
with GNU General Public License v3.0
from Faultify

public async Task<TestProjectReportModel> Test(MutationSessionProgressTracker progressTracker,
            CancellationToken cancellationToken = default)
        {
            // Build project
            progressTracker.LogBeginPreBuilding();
            var projectInfo = await BuildProject(progressTracker, _testProjectPath);
            progressTracker.LogEndPreBuilding();

            // Copy project N times
            progressTracker.LogBeginProjectDuplication(_parallel);
            var testProjectCopier = new TestProjectDuplicator(Directory.GetParent(projectInfo.replacedemblyPath).FullName);
            var duplications = testProjectCopier.MakeInitialCopies(projectInfo, _parallel);

            // Begin code coverage on first project.
            var duplicationPool = new TestProjectDuplicationPool(duplications);
            var coverageProject = duplicationPool.TakeTestProject();
            var coverageProjectInfo = GetTestProjectInfo(coverageProject, projectInfo);

            // Measure the test coverage 
            progressTracker.LogBeginCoverage();
            PreparereplacedembliesForCodeCoverage(coverageProjectInfo);

            var coverageTimer = new Stopwatch();
            coverageTimer.Start();
            var coverage = await RunCoverage(coverageProject.TestProjectFile.FullFilePath(), cancellationToken);
            coverageTimer.Stop();

            GC.Collect();
            GC.WaitForPendingFinalizers();

            coverageProject.FreeTestProject();

            // Start test session.
            var testsPerMutation = GroupMutationsWithTests(coverage);
            return StartMutationTestSession(coverageProjectInfo, testsPerMutation, progressTracker,
                coverageTimer.Elapsed, duplicationPool);
        }

19 Source : Program.cs
with MIT License
from filipw

static void Main(string[] args)
        {
            for (var i = 0; i < 3000; i++)
            {
                Executereplacedembly(i);
            }

            var compilation = CSharpCompilation.Create("Dynamicreplacedembly", new[] { CSharpSyntaxTree.ParseText(@"
            public clreplaced Greeter
            {
                public void Hello(int iteration)
                {
                    System.Console.WriteLine($""Hello in memory {iteration}!"");
                }
            }") },
            new[]
            {
                MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().replacedembly.Location),
                MetadataReference.CreateFromFile(typeof(Console).GetTypeInfo().replacedembly.Location),
                MetadataReference.CreateFromFile(SystemRuntime.Location),
            },
            new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            for (var i = 0; i < 3000; i++)
            {
                ExecuteInMemoryreplacedembly(compilation, i);
            }

            GC.Collect();
            GC.WaitForPendingFinalizers();

            Console.ReadKey();
        }

19 Source : BaseClientBrokerTestsSuite.cs
with Apache License 2.0
from finos

private void VerifyNoUnobservedTaskExceptions()
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            lock (_unobservedExceptions)
            {
                if (_unobservedExceptions.Count > 0)
                {
                    throw new AggregateException(
                        "Unhandled task exceptions after test run",
                        _unobservedExceptions);
                }
            }
        }

19 Source : PromiseTests.cs
with Apache License 2.0
from finos

private static void VerifyNoUnobservedTaskExceptions()
        {
            var list = new List<Exception>();

            void CatchUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs args)
            {
                lock (list)
                {
                    list.Add(args.Exception);
                }
            }

            TaskScheduler.UnobservedTaskException += CatchUnobservedTaskException;
            try
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                if (list.Count > 0)
                {
                    throw new AggregateException(list);
                }
            }
            finally
            {
                TaskScheduler.UnobservedTaskException -= CatchUnobservedTaskException;
            }
        }

19 Source : UIHandlerAutomated.cs
with Apache License 2.0
from firebase

Task TestCreateDestroy() {
        TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
        // Cleanup auth objects referenced by the sample application.
        auth = null;
        otherAuth = null;
        System.GC.Collect();
        System.GC.WaitForPendingFinalizers();
        // Kick off test on another thread.
        (new Thread(() => {
          Exception caughtException = null;
          try {
            // Create a named app using the default app options.
            Func<int, Firebase.FirebaseApp> createAnotherApp = (int appId) => {
              return Firebase.FirebaseApp.Create(
                Firebase.FirebaseApp.DefaultInstance.Options,
                String.Format("anotherapp_{0}", appId));
            };

            int currentAppId = 0;
            var CREATE_DESTROY_ITERATIONS = 100;
            // Dispose of an App object that is in use by an auth object.
            for (int i = 0; i < CREATE_DESTROY_ITERATIONS; ++i) {
              UnityEngine.Debug.Log(String.Format("Dispose app {0}/{1}", i + 1,
                                                  CREATE_DESTROY_ITERATIONS));
              var anotherApp = createAnotherApp(currentAppId++);
              var anotherAuth = Firebase.Auth.FirebaseAuth.GetAuth(anotherApp);
              // Dispose of the app which should dispose the replacedociated auth.
              anotherApp.Dispose();
              try {
                var user = anotherAuth.CurrentUser;
                // The exception can happen, but is not guaranteed, but we do
                // this to make sure it doesn't crash.
              } catch (NullReferenceException) {
                  // Do nothing here.
              }
              anotherApp = null;
              anotherAuth = null;
              System.GC.Collect();
              System.GC.WaitForPendingFinalizers();
            }

            // Ensure finalization of auth and app objects does not result in a crash due to out of
            // order destruction of native objects.
            for (int i = 0; i < CREATE_DESTROY_ITERATIONS; ++i) {
              UnityEngine.Debug.Log(String.Format("Finalize app and auth {0}/{1}", i + 1,
                                                  CREATE_DESTROY_ITERATIONS));
              var anotherApp = createAnotherApp(currentAppId++);
              var anotherAuth = Firebase.Auth.FirebaseAuth.GetAuth(anotherApp);
              UnityEngine.Debug.Log(String.Format("Created auth {0} for app {1}", anotherAuth,
                                                  anotherApp.Name));
              anotherApp = null;
              anotherAuth = null;
              System.GC.Collect();
              System.GC.WaitForPendingFinalizers();
            }
          } catch (Exception exception) {
            caughtException = exception;
          } finally {
            // Try to restore UIHandler's initial state.
            base.InitializeFirebase();
            // Ensure the initial state is restored before completing the Task
            if (caughtException != null) {
              tcs.SetException(caughtException);
            } else {
              tcs.SetResult(true);
            }
          }
        })).Start();
        return tcs.Task;
    }

19 Source : UIHandlerAutomated.cs
with Apache License 2.0
from firebase

Task TestCreateDestroy() {
      TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
      // Cleanup Installations object referenced by the sample application.
      installations = null;
      System.GC.Collect();
      System.GC.WaitForPendingFinalizers();
      // Kick off test on another thread.
      (new Thread(() => {
        Exception caughtException = null;
        try {
          var CREATE_DESTROY_ITERATIONS = 100;
          List<Task> taskList = new List<Task>();
          // Dispose of an App object that is in use by an installations object.
          for (int i = 0; i < CREATE_DESTROY_ITERATIONS; ++i) {
            UnityEngine.Debug.Log(String.Format("Dispose app {0}/{1}", i + 1,
                                                CREATE_DESTROY_ITERATIONS));
            var app = Firebase.FirebaseApp.DefaultInstance;
            installations = Firebase.Installations.FirebaseInstallations.GetInstance(app);
            app.Dispose();

            Task task = null;
            try {
              task = installations.GetIdAsync();
            } catch (System.NullReferenceException) {
              // Expecting NullReferenceException because installations should be disposed after
              // app is disposed.
            }

            if (task != null) {
              taskList.Add(task);
            }
            app = null;
            installations = null;
            System.GC.Collect();
            System.GC.WaitForPendingFinalizers();
          }

          // Make sure that the pending tasks have all finished before continuing.
          // Parse does not support WaitAll, so use WhenAll to combine to one task, then wait.
          Task.WhenAll(taskList.ToArray()).Wait();

          // Throw an exception and stop the test if GetIdAsync() did not throw a
          // NullReferenceException
          if (taskList.Count > 0) {
            throw new System.Exception("Expecting GetIdAsync() to thrown an exception");
          }

          // Ensure finalization of Installations and app objects does not result in a crash due to out of
          // order destruction of native objects.
          for (int i = 0; i < CREATE_DESTROY_ITERATIONS; ++i) {
            UnityEngine.Debug.Log(String.Format("Finalize app and Installations {0}/{1}", i + 1,
                                                CREATE_DESTROY_ITERATIONS));
            var app = Firebase.FirebaseApp.DefaultInstance;
            installations = Firebase.Installations.FirebaseInstallations.GetInstance(app);
            UnityEngine.Debug.Log(String.Format("Created Installations {0} for {1}", installations.App.Name,
                                                app.Name));
            app = null;
            installations = null;
            System.GC.Collect();
            System.GC.WaitForPendingFinalizers();
          }
        } catch (Exception exception) {
          caughtException = exception;
        } finally {
          // Try to restore UIHandler's initial state.
          installations = Firebase.Installations.FirebaseInstallations.DefaultInstance;
          UnityEngine.Debug.Log(
              String.Format("Recreated Installations for app {0}", installations.App.Name));

          // Postpone the task completion after installations is restore.  Otherwise, later tests
          // may be installations as null pointer.
          if (caughtException == null) {
            tcs.TrySetResult(true);
          } else {
            tcs.TrySetException(caughtException);
          }
        }
      })).Start();
      return tcs.Task;
    }

19 Source : UIHandlerAutomated.cs
with Apache License 2.0
from firebase

Task TestCreateDestroyRace() {
      TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
      // Cleanup Installations object referenced by the sample application.
      installations = null;
      System.GC.Collect();
      System.GC.WaitForPendingFinalizers();
      // Kick off test on another thread.
      (new Thread(() => {
        Exception caughtException = null;
        try {
          var CREATE_DESTROY_ITERATIONS = 100;
          // Dispose of an App object that is in use by an auth object.
          for (int i = 0; i < CREATE_DESTROY_ITERATIONS; ++i) {
            UnityEngine.Debug.Log(String.Format("Dispose app {0}/{1}", i + 1,
                                                CREATE_DESTROY_ITERATIONS));
            var app = Firebase.FirebaseApp.DefaultInstance;
            installations = Firebase.Installations.FirebaseInstallations.GetInstance(app);

            // Even though the app is destroyed, this call should not result in
            // any problems, other than returning a potentially faulted task.
            installations.GetIdAsync();

            app = null;
            installations = null;
            System.GC.Collect();
          }

          // Wait for pending finalizers for the next test
          System.GC.WaitForPendingFinalizers();

          // Ensure finalization of Installations and app objects does not result in a crash due to
          // out of order destruction of native objects.
          for (int i = 0; i < CREATE_DESTROY_ITERATIONS; ++i) {
            UnityEngine.Debug.Log(String.Format("Finalize app and Installations {0}/{1}", i + 1,
                                                CREATE_DESTROY_ITERATIONS));
            var app = Firebase.FirebaseApp.DefaultInstance;
            installations = Firebase.Installations.FirebaseInstallations.GetInstance(app);
            UnityEngine.Debug.Log(String.Format("Created Installations {0} for {1}",
                                                installations.App.Name, app.Name));
            app = null;
            installations = null;
            System.GC.Collect();
          }
        } catch (Exception exception) {
          caughtException = exception;
        } finally {
          // Wait for pending finalizers before restoring
          System.GC.WaitForPendingFinalizers();

          // Try to restore UIHandler's initial state.
          installations = Firebase.Installations.FirebaseInstallations.DefaultInstance;
          UnityEngine.Debug.Log(
              String.Format("Recreated Installations for app {0}", installations.App.Name));

          // Postpone the task completion after installations is restore.  Otherwise, later tests
          // may be installations as null pointer.
          if (caughtException == null) {
            tcs.SetResult(true);
          } else {
            tcs.SetException(caughtException);
          }
        }
      })).Start();
      return tcs.Task;
    }

19 Source : MainWindowViewModel.cs
with GNU General Public License v3.0
from fraxiinus

public async Task ClearCache()
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();

            if (ClearItemsCacheOnClose) { await RequestManager.ClearItemCache().ConfigureAwait(true); }
            if (ClearChampsCacheOnClose) { await RequestManager.ClearChampionCache().ConfigureAwait(true); }
            if (ClearRunesCacheOnClose) { await RequestManager.ClearRunesCache().ConfigureAwait(true); }

            if (ClearReplayCacheOnClose)
            {
                _fileManager.DeleteDatabase();
            }
        }

19 Source : AudioEditor.cs
with GNU General Public License v3.0
from Fraysa

public override void CustomDispose()
        {
            disposed = true;
            wavePlayer.Dispose();
            mpegStream.Dispose();
            byteStream.Dispose();
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }

19 Source : MainWindowEventHandlers.cs
with MIT License
from FutureAIGuru

private void button_FileNew_Click(object sender, RoutedEventArgs e)
        {
            if (PromptToSaveChanges())
            { } //cancel the operation
            else
            {
                SuspendEngine();
                //TODO: the following line unconditionally clobbers the current network
                //so the cancel button in the dialog won't work properly
                //CreateEmptyNetwork(); // to avoid keeping too many bytes occupied...

                // and make sure we have maximum memory free...
                GC.Collect();
                GC.WaitForPendingFinalizers();
                UpdateFreeMem();
                NewArrayDlg dlg = new NewArrayDlg();
                dlg.ShowDialog();
                if (dlg.returnValue)
                {
                    arrayView.Dp.NeuronDisplaySize = 62;
                    ButtonZoomToOrigin_Click(null, null);
                    currentFileName = "";
                    SetCurrentFileNameToProperties();
                    setreplacedleBar();
                    if (theNeuronArray.networkNotes != "")
                        MenuItemNotes_Click(null, null);
                }
                Update();
                ResumeEngine();
            }
        }

19 Source : Program.cs
with Apache License 2.0
from G-Research

public static int Main()
        {
            try
            {
                Console.WriteLine("Working directory: {0}", Environment.CurrentDirectory);

                AppDomain.CurrentDomain.UnhandledException += UncaughtExceptionHandler;

                //TestColumn.TestPrimitives();
                //TestParquetFileWriter.TestReadWriteParquetMultipleTasks();
                //TestColumnReader.TestHasNext();
                //TestLogicalTypeRoundtrip.TestRoundTrip(128, 2401, 1331, useDictionaryEncoding: true);
                //TestPhysicalTypeRoundtrip.TestReaderWriteTypes();
                //TestParquetFileReader.TestReadFileCreateByPython();
                //TestParquetFileReader.TestFileHandleHasBeenReleased();
                //TestParquetFileWriter.TestWriteLongString();
                //TestManagedRandomAccessFile.TestWriteException();
                //TestAadPrefixVerifier.TestOwnership();
                //TestEncryption.TestNoMatchingKeyMetadata();
                TestParquetFileWriter.TestProperties();
                //new TestMemoryLeaks().StressTestProcessMemory();

                // Ensure the finalizers are executed, so we can check whether they throw.
                GC.Collect();
                GC.WaitForPendingFinalizers();

                AppDomain.CurrentDomain.UnhandledException -= UncaughtExceptionHandler;

                return 0;
            }

            catch (Exception exception)
            {
                var colour = Console.ForegroundColor;

                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("ERROR: {0}", exception);
                Console.ForegroundColor = colour;
            }

            return 1;
        }

19 Source : TestParquetFileWriter.cs
with Apache License 2.0
from G-Research

[Test]
        public static void TestByteBufferOptimisation()
        {
            const int numStrings = 100_000;

            var strings = Enumerable.Range(0, numStrings).Select(i => i.ToString()).ToArray();

            var cancel = new CancellationTokenSource();
            var task = Task.Run(() =>
            {
                while (!cancel.IsCancellationRequested)
                {
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                    Thread.Sleep(1);
                }
            });

            using (var buffer = new ResizableBuffer())
            {
                using (var outStream = new BufferOutputStream(buffer))
                {
                    using var fileWriter = new ParquetFileWriter(outStream, new Column[] {new Column<string>("Name")});
                    using var groupWriter = fileWriter.AppendRowGroup();
                    using var columnWriter = groupWriter.NextColumn().LogicalWriter<string>();

                    // Strings to byte arrays memory pooling is done by the ByteBuffer clreplaced.
                    // If something is fishy there (e.g. bad memory ownership wrt the GC),
                    // we expect to see consequences here if we write enough strings.
                    // It's not bullet proof, but it has found a few issues.
                    columnWriter.WriteBatch(strings);

                    fileWriter.Close();
                }

                using var inStream = new BufferReader(buffer);
                using var fileReader = new ParquetFileReader(inStream);
                using var groupReader = fileReader.RowGroup(0);
                using var columnReader = groupReader.Column(0).LogicalReader<string>();

                replacedert.AreEqual(strings, columnReader.ReadAll(numStrings));
            }

            cancel.Cancel();
            task.Wait();
        }

19 Source : WmcStore.cs
with MIT License
from garyan2

public static void Close(bool dispose = false)
        {
            if (objectStore != null)
            {
                objectStore.StoreExpired -= WmcObjectStore_StoreExpired;
                ObjectStore.ReleaseObjectStoreReference();
            }
            wmcMergedLineup = null;

            try
            {
                if (dispose)
                {
                    objectStore?.Dispose();
                }
            }
            catch (Exception ex)
            {
                Logger.WriteInformation($"Exception thrown while trying to dispose of ObjectStore. {ex.Message}\n{ex.StackTrace}");
            }
            objectStore = null;
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
        }

19 Source : DBCacheService.cs
with MIT License
from gatosyocora

public async Task DeleteAll()
        {
            await _context.DisposeAsync();
            GC.Collect();
            GC.WaitForPendingFinalizers();
            File.Delete(_dbFilePath);
        }

19 Source : Extensions.cs
with MIT License
from genesisdotnet

public static void Unloadreplacedembly(this WeakReference weakRef, bool waitUntilFinished = true)
        {
            ((GenesisreplacedemblyLoadContext)weakRef.Target).Unload();

            if (!waitUntilFinished)
                return;

            for (var i = 0; weakRef.IsAlive && (i < 10); i++) //NOTE: Don't have to wait if we don't want to, GC will eventually get it. 
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }

19 Source : Program.cs
with MIT License
from GGG-KILLER

[Command("gc")]
        [HelpDescription("Invokes the garbage collector")]
        public static void InvokeGC()
        {
            for (var idx = 0; idx < 1000; idx++)
            {
                GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true, compacting: true);
                GC.WaitForPendingFinalizers();
            }
        }

19 Source : ObjectReference.cs
with MIT License
from GGG-KILLER

[MethodImpl(MethodImplOptions.NoInlining)]
        private void ReleaseAndGarbageCollect(bool expectReleased)
        {
            if (_strongReferenceRetrievedOutsideScopedCall)
            {
                throw new InvalidOperationException($"The strong reference being held by the {nameof(ObjectReference<T>)} was retrieved via a call to {nameof(GetReference)}. Since the CLR might have cached a temporary somewhere in your stack, replacedertions can no longer be made about the correctness of lifetime.");
            }

            _strongReference = null;

            // The maximum number of iterations is determined by the expected outcome. If we expect the reference to be
            // released, we loop many more times to avoid flaky test failures. Otherwise, we loop a few times knowing
            // that the test will probably catch the failure on any given run. This strategy trades produces a few false
            // negatives in testing to gain a significant performance advantage for the majority case.
            var loopCount = expectReleased ? 1000 : 10;

            // We'll loop until the iteration count is reached, or until the weak reference disappears. When we're
            // trying to replacedert that the object is released, once the weak reference goes away, we know we're good. But
            // if we're trying to replacedert that the object is held, our only real option is to know to do it "enough"
            // times; but if it goes away then we are definitely done.
            for (var i = 0; i < loopCount && _weakReference.IsAlive; i++)
            {
                GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true, compacting: true);
                GC.WaitForPendingFinalizers();
            }
        }

19 Source : Program.cs
with MIT License
from GGG-KILLER

private static void InvokeGC()
        {
            for (var idx = 0; idx < 25; idx++)
            {
                GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true, compacting: true);
                GC.WaitForPendingFinalizers();
            }
        }

19 Source : Program.cs
with Apache License 2.0
from ghi-electronics

static void DoDraw() {
            try {
                var sd = StorageController.FromName(SC20260.StorageController.SdCard);
                var drive = FileSystem.Mount(sd.Hdc);
                var spiController = SpiController.FromName(SC20260.SpiBus.Spi5);

                var ledController = new APA102CController(spiController, (PanelsWide * PanelsHigh) << 8);

                var stream = new FileStream(@"A:\output.avi", FileMode.Open);

                var aviDecoder = new AviDecoder(stream);

                var fpsCounter = 0;
                var oneSecondStart = DateTime.Now;

                var textColor = new SolidBrush(Color.White);

                aviDecoder.Run();

                var frameCounter = 0;
                var pauseCounter = 0;

                while (true) {
                    var t1 = DateTime.Now;

                    if (pauseApp == true && pauseCounter > 0) {
                        goto display_text;
                    }

                    pauseCounter = pauseApp ? (pauseCounter + 1) : 0;

                    try {
                        Bitmap bitmap;
                        bitmap = aviDecoder.GetBimap();

                        screen.Clear();

                        if (bitmap != null) {
                            var data = NativeCookData(bitmap, (byte)(0b1110_0000 | intensity));

                            ledController.SetBuffer(data, 0, data.Length);

                            for (var i = 0; i < 2; i++) // flush twice to fix pannel 5 mesy sometime
                                ledController.Flush();

                            screen.DrawImage(bitmap, (LcdWidth - bitmap.Width) >> 1, (LcdHeight - bitmap.Height) >> 1);
                        }
                    }
                    catch {

                    }

display_text:

                    screen.DrawString("Status: " + (frameCounter < 1 ? "Loading... " : (pauseApp ? "Paused" : "Playing")), font, textColor, 10, 10);
                    screen.DrawString("Intensity: " + intensity, font, textColor, 10, 30);

                    screen.Flush();

                    frameCounter++;

                    if (frameCounter % 10 == 0) {
                        GC.Collect();
                        GC.WaitForPendingFinalizers();
                    }

                    Thread.Sleep(1);

                    if (aviDecoder != null && aviDecoder.headerInfo != null && aviDecoder.headerInfo.TimeBetweenFrames != 0) {
                        var t2 = DateTime.Now - t1;

                        if (t2.TotalMilliseconds < aviDecoder.headerInfo.TimeBetweenFrames) {
                            Thread.Sleep(aviDecoder.headerInfo.TimeBetweenFrames - (int)t2.TotalMilliseconds);
                        }

                        fpsCounter++;

                        var oneSecondEnd = DateTime.Now - oneSecondStart;
                        if (oneSecondEnd.TotalMilliseconds >= 1000) {
                            Debug.WriteLine("Fps = " + fpsCounter);
                            fpsCounter = 0;
                            oneSecondStart = DateTime.Now;
                        }
                    }
                }
            }
            catch {
                screen.Clear();
                screen.DrawString("Loading file from sd card failed.", font, new SolidBrush(Color.Red), 10, 10);
                screen.DrawString("Check the card and Reset application.", font, new SolidBrush(Color.Red), 10, 30);

                screen.Flush();

            }
        }

19 Source : ApplicationWindow.cs
with Apache License 2.0
from ghi-electronics

public UIElement Open() {
            if (!this.actived) {

                // Avoid defregment if next screen allocate big memory
                GC.Collect();
                GC.WaitForPendingFinalizers();

                //Debug.WriteLine("" + GHIElectronics.TinyCLR.Native.Memory.ManagedMemory.FreeBytes / 1024);


                this.topBar = sTopBar;// new TopBar(this.Width, this.Icon.IconText, this.EnableClockOnTopBar);
                //this.topBar.OnClose += this.OnClose;

                if (this.EnableButtomBack || this.EnableButtomNext) {
                    this.bottomBar = sBottomBar;// new BottomBar(this.Width, this.EnableButtomBack, this.EnableButtomNext);
                }

                try {
                    this.Active();
                }
                catch {
                    return null;
                }

                if (this.EnableButtomBack || this.EnableButtomNext) {
                    this.Child.AddHandler(Buttons.ButtonUpEvent, new RoutedEventHandler(this.OnButtonUp), true);
                    this.Child.IsVisibleChanged += this.Child_IsVisibleChanged;

                    if (this.EnableButtomBack) {
                        this.bottomBar.ButtonBack.Click += this.ButtonBack_Click;
                    }

                    if (this.EnableButtomNext) {
                        this.bottomBar.ButtonNext.Click += this.ButtonNext_Click;
                    }
                }

                this.actived = true;
            }



            return this.Child;
        }

19 Source : ApplicationWindow.cs
with Apache License 2.0
from ghi-electronics

public void UpdateStatusText(TextFlow textFlow, string text, Font font, bool clearscreen, Color color) {

            var timeout = 100;
            var count = 0;

            if (textFlow == null)
                goto _return;

            lock (textFlow) {

                count = textFlow.TextRuns.Count + 2;
            }

            Application.Current.Dispatcher.Invoke(TimeSpan.FromMilliseconds(timeout), _ => {

                if (textFlow == null)
                    return null;

                lock (textFlow) {
                    if (clearscreen)
                        textFlow.TextRuns.Clear();

                    textFlow.TextRuns.Add(text, font, GHIElectronics.TinyCLR.UI.Media.Color.FromRgb(color.R, color.G, color.B));
                    textFlow.TextRuns.Add(TextRun.EndOfLine);

                    return null;
                }

            }, null);

            if (textFlow == null)
                goto _return;

            lock (textFlow) {

                if (clearscreen) {
                    while (textFlow.TextRuns.Count < 2) {
                        Thread.Sleep(1);
                    }
                }
                else {
                    while (textFlow.TextRuns.Count < count) {
                        Thread.Sleep(1);
                    }
                }
            }
_return:
            GC.Collect();
            GC.WaitForPendingFinalizers();

        }

19 Source : MainWindow.cs
with Apache License 2.0
from ghi-electronics

private void OnButtonUp(object sender, RoutedEventArgs e) {
            var buttonSource = (GHIElectronics.TinyCLR.UI.Input.ButtonEventArgs)e;

            this.selectWindowIndexPrev = this.selectWindowIndex;

            switch (buttonSource.Button) {
                case GHIElectronics.TinyCLR.UI.Input.HardwareButton.Left:
                    if (this.selectWindowIndex == this.applicationWindows.Count - 1) {
                        this.selectWindowIndex = 0;
                    }
                    else {
                        this.selectWindowIndex++;
                    }

                    this.animationStep = -MaxStep;


                    break;

                case GHIElectronics.TinyCLR.UI.Input.HardwareButton.Right:
                    if (this.selectWindowIndex == 0) {
                        this.selectWindowIndex = this.applicationWindows.Count - 1;
                    }
                    else {
                        this.selectWindowIndex--;
                    }

                    this.animationStep = MaxStep;

                    break;

                case GHIElectronics.TinyCLR.UI.Input.HardwareButton.Select:
                    this.animationStep = 0;

                    GC.Collect();
                    GC.WaitForPendingFinalizers();

                    var applicationWindow = (ApplicationWindow)this.applicationWindows[this.selectWindowIndex];

                    var nextWindow = applicationWindow.Open();

                    if (nextWindow != null)
                        this.Child = nextWindow;

                    break;

            }

            Application.Current.Dispatcher.Invoke(TimeSpan.FromMilliseconds(1000), _ => { this.UpdateScreen(); return null; }, null);

        }

19 Source : Sd.cs
with Apache License 2.0
from ghi-electronics

private void ThreadTest() {
            const int BlockSize = 1024;

            this.isRuning = true;

            var data = System.Text.Encoding.UTF8.GetBytes("Thi is for sd  \n");

            // Defragment memory
            GC.Collect();
            GC.WaitForPendingFinalizers();

            var dataWrite = new byte[BlockSize];
            var dataRead = new byte[BlockSize];

            for (var i = 0; i < BlockSize; i += data.Length) {
                Array.Copy(data, 0, dataWrite, i, data.Length);
            }

            var storageController = StorageController.FromName(SC20260.StorageController.SdCard);

            IDriveProvider drive;


            try {
                drive = FileSystem.Mount(storageController.Hdc);

                var driveInfo = new DriveInfo(drive.Name);

                this.UpdateStatusText(FreeSize + driveInfo.TotalFreeSpace, true);
                this.UpdateStatusText(TotalSize + driveInfo.TotalSize, false);
                this.UpdateStatusText(VolumeLabel + driveInfo.VolumeLabel, false);
                this.UpdateStatusText(RootDirectory + driveInfo.RootDirectory, false);
                this.UpdateStatusText(DriveFormat + driveInfo.DriveFormat, false);
                this.UpdateStatusText(MountSuccess, false);

            }
            catch {

                this.UpdateStatusText(BadConnect1, true);

                goto _return;
            }

            Thread.Sleep(1000);

            var filename = drive.Name + "\\TEST_SD.TXT";

            try {
                using (var fsWrite = new FileStream(filename, FileMode.Create)) {

                    fsWrite.Write(dataWrite, 0, dataWrite.Length);

                    fsWrite.Flush();
                    fsWrite.Close();
                }
            }
            catch {
                this.UpdateStatusText(BadWrite, false);

                goto _unmount;
            }

            try {
                using (var fsRead = new FileStream(filename, FileMode.Open)) {

                    fsRead.Read(dataRead, 0, dataRead.Length);

                    for (var i = 0; i < dataRead.Length; i++) {


                        if (dataRead[i] != dataWrite[i]) {
                            this.UpdateStatusText(BadConnect2, false);

                            goto _unmount;
                        }
                    }

                    fsRead.Flush();
                    fsRead.Close();
                }
            }
            catch {
                this.UpdateStatusText(BadRead, false);

                goto _unmount;
            }


            this.UpdateStatusText(TestSuccess, false);

_unmount:
            try {
                GHIElectronics.TinyCLR.IO.FileSystem.Flush(storageController.Hdc);
                GHIElectronics.TinyCLR.IO.FileSystem.Unmount(storageController.Hdc);
            }
            catch {
            }

_return:

            this.isRuning = false;

        }

19 Source : ApplicationWindow.cs
with Apache License 2.0
from ghi-electronics

public UIElement Open() {
            if (!this.actived) {

                GC.Collect();
                GC.WaitForPendingFinalizers();

                //Debug.WriteLine("" + GHIElectronics.TinyCLR.Native.Memory.ManagedMemory.FreeBytes / 1024);

                this.topBar = new TopBar(this.Width, this.Icon.IconText, this.EnableClockOnTopBar);
                this.topBar.OnClose += this.OnClose;

                if (this.EnableButtonBack || this.EnableButtonNext) {
                    this.bottomBar = new BottomBar(this.Width, this.EnableButtonBack, this.EnableButtonNext);
                }


                this.Active();

                if (this.EnableButtonBack || this.EnableButtonNext) {
                    this.Child.AddHandler(Buttons.ButtonUpEvent, new RoutedEventHandler(this.OnButtonUp), true);
                    this.Child.IsVisibleChanged += this.Child_IsVisibleChanged;

                    if (this.EnableButtonBack) {
                        this.bottomBar.ButtonBack.Click += this.ButtonBack_Click;
                    }

                    if (this.EnableButtonNext) {
                        this.bottomBar.ButtonNext.Click += this.ButtonNext_Click;
                    }
                }

                this.actived = true;
            }



            return this.Child;
        }

19 Source : MainWindow.cs
with Apache License 2.0
from ghi-electronics

public void Open() {
            GC.Collect();
            GC.WaitForPendingFinalizers();

            this.Child = this.mainStackPanel;
        }

19 Source : Adc.cs
with Apache License 2.0
from ghi-electronics

private void UpdateStatusText(string text, bool clearscreen, System.Drawing.Color color) {

            var timeout = 100;

            try {

                var count = this.textFlow.TextRuns.Count + 2;

                Application.Current.Dispatcher.Invoke(TimeSpan.FromMilliseconds(timeout), _ => {

                    if (clearscreen)
                        this.textFlow.TextRuns.Clear();

                    this.textFlow.TextRuns.Add(text, this.font, GHIElectronics.TinyCLR.UI.Media.Color.FromRgb(color.R, color.G, color.B));
                    this.textFlow.TextRuns.Add(TextRun.EndOfLine);

                    return null;

                }, null);

                if (clearscreen) {
                    while (this.textFlow.TextRuns.Count < 2) {
                        Thread.Sleep(10);
                    }
                }
                else {
                    while (this.textFlow.TextRuns.Count < count) {
                        Thread.Sleep(10);
                    }
                }
            }
            catch {

            }

            GC.Collect();
            GC.WaitForPendingFinalizers();

        }

19 Source : ColorWindow.cs
with Apache License 2.0
from ghi-electronics

private void ThreadTest() {

            this.isRunning = true;


            var displayController = Display.DisplayController;

            var screen = System.Drawing.Graphics.FromHdc(displayController.Hdc);

            var background = Resources.GetBitmap(Resources.BitmapResources.Color);

            var startY = 0;
            var imageX = 0;

            var screen_width = 480;
            var screen_height = 272 - this.TopBar.ActualHeight;

            while (this.isRunning) {

                screen.Clear();

                screen.DrawImage(background, imageX, startY);

                screen.FillEllipse(new SolidBrush(System.Drawing.Color.FromArgb(100, 0xFF, 0, 0)), 0, startY, 100, 100);


                screen.FillRectangle(new SolidBrush(System.Drawing.Color.FromArgb(100, 0, 0, 0xFF)), 0, 120, screen_width / 4, screen_height - 120);
                screen.FillRectangle(new SolidBrush(System.Drawing.Color.FromArgb(100, 0, 0xFF, 0)), screen_width / 4, 120, screen_width / 4, screen_height - 120);
                screen.FillRectangle(new SolidBrush(System.Drawing.Color.FromArgb(100, 0xFF, 0, 0)), screen_width / 4 * 2, 120, screen_width / 4, screen_height - 120);
                screen.FillRectangle(new SolidBrush(System.Drawing.Color.FromArgb(100, 0xFF, 0xFF, 0xFF)), screen_width / 4 * 3, 120, screen_width / 4, screen_height - 120);


                screen.DrawString("This is blue", this.font, new SolidBrush(System.Drawing.Color.Blue), 0, screen_height - 140);
                screen.DrawString("This is green", this.font, new SolidBrush(System.Drawing.Color.Green), screen_width / 4, screen_height - 140);
                screen.DrawString("This is red", this.font, new SolidBrush(System.Drawing.Color.Red), screen_width / 4 * 2, screen_height - 140);
                screen.DrawString("This is white", this.font, new SolidBrush(System.Drawing.Color.White), screen_width / 4 * 3, screen_height - 140);
                screen.DrawString("Touch here to return main menu [X]", this.font, new SolidBrush(System.Drawing.Color.White), screen_width / 2, 5);




                screen.Flush();

                GC.Collect();
                GC.WaitForPendingFinalizers();
            }


            this.isRunning = false;

            return;

        }

19 Source : QspiWindow.cs
with Apache License 2.0
from ghi-electronics

private void ThreadTest() {

            this.isRuning = true;
            var storeController = StorageController.FromName(SC20260.StorageController.QuadSpi);

            var drive = storeController.Provider;

            drive.Open();


            var sectorSize = drive.Descriptor.RegionSizes[0];

            var textWrite = System.Text.UTF8Encoding.UTF8.GetBytes("this is for test");

            GC.Collect();
            GC.WaitForPendingFinalizers();

            var dataRead = new byte[sectorSize];
            var dataWrite = new byte[sectorSize];

            for (var i = 0; i < sectorSize; i += textWrite.Length) {
                Array.Copy(textWrite, 0, dataWrite, i, textWrite.Length);

            }

            var roundTest = 0;
            var startSector = 0;
            var endSector = 8;

_again:
            if (roundTest == 1) {
                startSector = 4088; // last 8 sectors
                endSector = startSector + 8;
            }

            for (var s = startSector; s < endSector; s++) {
                var address = s * sectorSize;
                this.UpdateStatusText("Erasing sector " + s, true);

                // Erase
                drive.Erase(address, sectorSize, TimeSpan.FromSeconds(100));

                // Write
                this.UpdateStatusText("Writing sector " + s, false);
                drive.Write(address, sectorSize, dataWrite, 0, TimeSpan.FromSeconds(100));

                this.UpdateStatusText("Reading sector " + s, false);
                //Read to compare
                drive.Read(address, sectorSize, dataRead, 0, TimeSpan.FromSeconds(100));


                for (var idx = 0; idx < sectorSize; idx++) {
                    if (dataRead[idx] != dataWrite[idx]) {

                        this.UpdateStatusText("Compare failed at: " + idx, false);

                        goto _return;
                    }

                }
            }

            roundTest++;

            if (roundTest == 2) {
                this.UpdateStatusText("Tested Quad Spi successful!", false);
            }
            else {
                goto _again;
            }


_return:
            drive.Close();
            this.isRuning = false;

            return;

        }

19 Source : MainWindow.cs
with Apache License 2.0
from ghi-electronics

public void RegisterWindow(ApplicationWindow aw) {

            GC.Collect();
            GC.WaitForPendingFinalizers();


            aw.Parent = this;
            aw.Id = this.applicationWindows.Count;
            aw.Icon.Width = this.Width / IconColum;
            aw.Icon.Height = aw.Icon.Width + (3 * aw.Icon.Font.Height) / 2;

            this.applicationWindows.Add(aw);


            if (this.applicationWindows.Count >= IconColum)
                this.UpdateScreen();

        }

19 Source : MainWindow.cs
with Apache License 2.0
from ghi-electronics

public void RegisterWindow(ApplicationWindow aw) {
            if (this.applicationWindows.Count == MaxWindows)
                throw new ArgumentOutOfRangeException("No more than " + MaxWindows + " windows");

            GC.Collect();
            GC.WaitForPendingFinalizers();

            aw.Parent = this;
            aw.Id = this.applicationWindows.Count;
            aw.Icon.Width = this.Width / IconColum;
            aw.Icon.Height = aw.Icon.Width;

            var r = this.applicationWindows.Count / IconColum;

            this.applicationWindows.Add(aw);

            this.iconStackPanels[r].Children.Clear();

            for (var i = 0; i < IconColum; i++) {
                if (r * IconColum + i >= this.applicationWindows.Count)
                    break;

                var a = (ApplicationWindow)this.applicationWindows[r * IconColum + i];

                if (a != null) {
                    this.iconStackPanels[r].Children.Add(a.Icon);                    
                    a.Icon.Click += this.Icon_Click;
                }
            }

            this.UpdateScreen();            
        }

19 Source : Program.cs
with Apache License 2.0
from ghi-electronics

static void Main()
        {
            var adcController = AdcController.FromName(SC20100.AdcChannel.Controller1.Id);

            var adcChannel = adcController.OpenChannel(SC20100.AdcChannel.Controller1.PA0);

            var strobePin = GpioController.GetDefault().OpenPin(SC20100.GpioPin.PE1);
            var resetPin = GpioController.GetDefault().OpenPin(SC20100.GpioPin.PE0);

            var msgeq7 = new Msgeq7(adcChannel, strobePin, resetPin);

            InitializeSPIDisplay();

            while (true)
            {
                msgeq7.UpdateBands();

                DrawEqualizer(msgeq7.Data);

                GC.Collect();

                GC.WaitForPendingFinalizers();
            }

        }

19 Source : MainWindow.xaml.cs
with MIT License
from ghost1372

private void ForceGC(object sender, RoutedEventArgs e)
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }

19 Source : RevokeNotifierTestClass.cs
with Apache License 2.0
from gigya

public static void CallGC()
        {
            GC.WaitForFullGCComplete();
            GC.WaitForPendingFinalizers();
            GC.WaitForFullGCApproach();
            GC.Collect(2);
        }

19 Source : OrleansToNinjectBindingTests.cs
with Apache License 2.0
from gigya

[TestCase(ServiceProviderType.microdot)]
        [TestCase(ServiceProviderType.microsoft)]
        public void Scope_dependency_should_be_rooted_to_scope(ServiceProviderType serviceProviderType)
        {
            var binding = new ServiceCollection().AddScoped<Dependency>();
            var serviceProvider = CreateServiceProvider(binding, serviceProviderType);
            var serviceScopeFactory = (IServiceScopeFactory)serviceProvider.GetService(typeof(IServiceScopeFactory));

            var scope = serviceScopeFactory.CreateScope();
            WeakReference<object> holder = null;
            Action notRootByDebuger = () =>
            {
                holder = new WeakReference<object>(scope.ServiceProvider.GetService(typeof(Dependency)));
            };
            notRootByDebuger();
            MakeSomeGarbage();

            GC.WaitForFullGCComplete();
            GC.WaitForPendingFinalizers();
            GC.WaitForFullGCApproach();
            GC.Collect(2);

            replacedert.True(holder.TryGetTarget(out _), "Dependency is rooted to scoped, it should  be collected");
            scope.Dispose();
        }

19 Source : OrleansToNinjectBindingTests.cs
with Apache License 2.0
from gigya

[TestCase(ServiceProviderType.microdot)]
        [TestCase(ServiceProviderType.microsoft)]
        public void Singleton_Dependency_should_be_rooted(ServiceProviderType serviceProviderType)
        {
            var binding = new ServiceCollection().AddSingleton<Dependency>();
            var serviceProvider = CreateServiceProvider(binding, serviceProviderType);

            WeakReference<object> holder = null;
            Action notRootByDebuger = () =>
            {
                holder = new WeakReference<object>(serviceProvider.GetService(typeof(Dependency)));
            };
            notRootByDebuger();
            MakeSomeGarbage();

            GC.WaitForFullGCComplete();
            GC.WaitForPendingFinalizers();
            GC.WaitForFullGCApproach();
            GC.Collect(2);


            replacedert.True(holder.TryGetTarget(out _), "Dependency is rooted to scoped, it should  be collected");
        }

19 Source : OrleansToNinjectBindingTests.cs
with Apache License 2.0
from gigya

[TestCase(ServiceProviderType.microdot)]
        [TestCase(ServiceProviderType.microsoft)]
        public void Scope_should_not_be_rooted(ServiceProviderType serviceProviderType)
        {
            var binding = new ServiceCollection().AddScoped<Dependency>();
            var serviceProvider = CreateServiceProvider(binding, serviceProviderType);
            var serviceScopeFactory = (IServiceScopeFactory)serviceProvider.GetService(typeof(IServiceScopeFactory));

            WeakReference<object> holder = null;
            Action notRootByDebuger = () =>
            {
                holder = new WeakReference<object>(serviceScopeFactory.CreateScope());

            };
            notRootByDebuger();
            MakeSomeGarbage();

            GC.WaitForFullGCComplete();
            GC.WaitForPendingFinalizers();
            GC.WaitForFullGCApproach();
            GC.Collect(2);

            replacedert.False(holder.TryGetTarget(out _), "scope object in not rooted, it should be collected");
        }

19 Source : OrleansToNinjectBindingTests.cs
with Apache License 2.0
from gigya

[TestCase(ServiceProviderType.microdot)]
        [TestCase(ServiceProviderType.microsoft)]
        public void Scope_Dependency_should_not_be_rootd(ServiceProviderType serviceProviderType)
        {
            var binding = new ServiceCollection().AddScoped<Dependency>();
            var serviceProvider = CreateServiceProvider(binding, serviceProviderType);
            var serviceScopeFactory = (IServiceScopeFactory)serviceProvider.GetService(typeof(IServiceScopeFactory));

            WeakReference<object> holder = null;
            Action notRootByDebuger = () =>
            {
                holder = new WeakReference<object>(serviceScopeFactory.CreateScope().ServiceProvider.GetService(typeof(Dependency)));
            };
            notRootByDebuger();
            MakeSomeGarbage();

            GC.WaitForFullGCComplete();
            GC.WaitForPendingFinalizers();
            GC.WaitForFullGCApproach();
            GC.Collect(2);


            replacedert.False(holder.TryGetTarget(out _), "scope object in not rooted, it should be collected");
        }

19 Source : OrleansToNinjectBindingTests.cs
with Apache License 2.0
from gigya

[TestCase(ServiceProviderType.microdot)]
        /*
         The behavior of Microsoft.Extensions.DependencyInjection.Abstractions seems to have changed between (2.2) => (3.1.3)
         Since we are not using it anymore for Scopes it is not an issue but if we decide to go back to it, this is a strong 
         indication that scoped object will leak.
         
        [TestCase(ServiceProviderType.microsoft)]
        */
        public void When_scope_dispose_should_realece_referaces_to_scope_dependency(ServiceProviderType serviceProviderType)
        {
            var binding = new ServiceCollection().AddScoped<Dependency>();
            var serviceProvider = CreateServiceProvider(binding, serviceProviderType);
            var serviceScopeFactory = (IServiceScopeFactory)serviceProvider.GetService(typeof(IServiceScopeFactory));

            var scope = serviceScopeFactory.CreateScope();
            WeakReference<object> holder = null;
            Action notRootByDebuger = () =>
            {
                holder = new WeakReference<object>(scope.ServiceProvider.GetService(typeof(Dependency)));
            };
            notRootByDebuger();
            scope.Dispose();
            MakeSomeGarbage();

            GC.WaitForFullGCComplete();
            GC.WaitForPendingFinalizers();
            GC.WaitForFullGCApproach();
            GC.Collect(2);


            replacedert.False(holder.TryGetTarget(out _), "scope object in not rooted, it should be collected");
        }

19 Source : DisposableTest.cs
with MIT License
from gimlichael

[Fact]
        public void UnmanagedDisposable_VerifyThatreplacedetIsBeingDisposedOnFinalize()
        {
            Action body = () =>
            {
                var o = new UnmanagedDisposable();
                replacedert.NotEqual(IntPtr.Zero, o._libHandle);
                replacedert.NotEqual(IntPtr.Zero, o._handle);
                unmanaged = new WeakReference<UnmanagedDisposable>(o, true);
            };

            try
            {
                body();
            }
            finally
            {
                GC.Collect(0, GCCollectionMode.Forced);
                GC.WaitForPendingFinalizers();
            }

            Thread.Sleep(3500); // await GC

            if (unmanaged.TryGetTarget(out var ud2))
            {
                replacedert.True(ud2.Disposed);
            }
        }

19 Source : ActVisualTestingEditPage.xaml.cs
with Apache License 2.0
from Ginger-Automation

private void DeleteOldFile(String FileToDelete)
        {
            if (File.Exists(FileToDelete))
            {
                System.GC.Collect();
                System.GC.WaitForPendingFinalizers();
                File.Delete(FileToDelete);
            }
        }

19 Source : UIAutomationDriverBase.cs
with Apache License 2.0
from Ginger-Automation

internal void CheckAndRetryRunAction(Act act, Exception e)
        {
            if (!retryForCOMExceptionDoneFlag && mUIAutomationHelper.GetCurrentWindow() != null && mUIAutomationHelper.CurrentWindowRootElement != null && mUIAutomationHelper.CurrentWindowRootElement.ElementName != null)
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
                retryForCOMExceptionDoneFlag = true;
                mUIAutomationHelper.SwitchToWindow(mUIAutomationHelper.CurrentWindowRootElement.ElementName);
                Reporter.ToLog(eLogLevel.DEBUG, "Retrying the action" + act.GetType() + " Description is" + act.Description);
                RunAction(act);
                retryForCOMExceptionDoneFlag = false;
            }
            else
            {
                act.Error = e.Message;
            }
        }

19 Source : MemoryManagementTest.cs
with MIT License
from gircore

[TestMethod]
        public void TestAutomaticGObjectDisposal()
        {
            WeakReference weakReference = new(null);
            IDisposable? strongReference = null;

            void CreateInstance(bool keepInstance)
            {
                var obj = Pixbuf.NewFromFile("test.bmp");

                GObject.Native.ObjectMapper.ObjectCount.Should().Be(1);

                if (keepInstance)
                    strongReference = obj;

                weakReference.Target = obj;
            }

            CreateInstance(keepInstance: false);

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GObject.Native.ObjectMapper.ObjectCount.Should().Be(0);
            weakReference.IsAlive.Should().BeFalse();
            strongReference.Should().BeNull();

            CreateInstance(keepInstance: true);
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GObject.Native.ObjectMapper.ObjectCount.Should().Be(1);
            weakReference.IsAlive.Should().BeTrue();
            strongReference.Should().NotBeNull();

            // Cleanup: Dispose for other tests to work properly
            // It looks like the GC is not collecting the ObjectMapper data
            // if the GC.Collect() call is happening in the method which
            // contains the reference to be freed. There must be a context
            // switch before disposal happens.
            // This is the reason why we need to use the "CreateInstance"
            // method to create the instances which should be freed.
            // This behaviour is verified on Linux.
            strongReference.Dispose();
        }

19 Source : MapData.cs
with GNU Affero General Public License v3.0
from gispeople

public void CloseService(string layerId)
        {
            // don't try to close a non-existent service
            if (!_layerDict.ContainsKey(layerId)) return;
            _layerDict[layerId].Close();
            _layerDict.Remove(layerId);
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }

19 Source : GloabalContext.cs
with MIT License
from GmodNET

int UnloadModule(ILua lua)
        {
            try
            {
                string module_name = lua.GetString(1);

                if (String.IsNullOrEmpty(module_name))
                {
                    throw new Exception("Module name is empty or null");
                }

                if (!module_contexts.ContainsKey(module_name))
                {
                    throw new Exception($"There is no loaded module with name { module_name }");
                }

                lua.PrintToConsole($"Unloading module { module_name } ...");

                WeakReference<GmodNetModulereplacedemblyLoadContext> context_weak_reference = UnloadHelper(module_name);

                for(int i = 0; context_weak_reference.TryGetTarget(out _); i++)
                {
                    lua.PushSpecial(SPECIAL_TABLES.SPECIAL_GLOB);
                    lua.GetField(-1, "collectgarbage");
                    lua.MCall(0, 0);
                    lua.Pop(1);

                    GC.Collect();
                    GC.WaitForPendingFinalizers();

                    if(i >= 300)
                    {
                        throw new Exception($"Module {module_name} can't be unloaded: there are remaining references or background threads still executing. " +
                            $"Module resources can't be freed. Memory leak could occur. Game restart may be required.");
                    }
                }

                lua.PrintToConsole($"Module {module_name} was unloaded.");

                lua.PushBool(true);

                return 1;
            }
            catch (Exception e)
            {
                lua.PrintToConsole("Unable to unload module: exception was thrown");
                lua.PrintToConsole(e.ToString());

                lua.PushBool(false);

                return 1;
            }
        }

19 Source : GloabalContext.cs
with MIT License
from GmodNET

internal void OnNativeUnload(ILua lua)
        {
            try
            {
                List<string> module_names = new List<string>();

                foreach (var p in module_contexts)
                {
                    module_names.Add(p.Key);
                }

                foreach(string name in module_names)
                {
                    try
                    {
                        WeakReference<GmodNetModulereplacedemblyLoadContext> weak_reference = UnloadHelper(name);

                        for (int i = 0; weak_reference.TryGetTarget(out _); i++)
                        {
                            lua.PushSpecial(SPECIAL_TABLES.SPECIAL_GLOB);
                            lua.GetField(-1, "collectgarbage");
                            lua.MCall(0, 0);
                            lua.Pop(1);

                            GC.Collect();
                            GC.WaitForPendingFinalizers();

                            if (i >= 300)
                            {
                                throw new Exception($"Module {name} can't be unloaded: there are remaining references or background threads still executing. " +
                                    $"Module resources can't be freed. Memory leak could occur. Game restart may be required.");
                            }
                        }
                    }
                    catch(Exception e)
                    {
                        lua.PrintToConsole($"Exception was thrown while unloading .NET module {name}");
                        lua.PrintToConsole(e.ToString());
                    }
                }
            }
            catch(Exception e)
            {
                lua.PrintToConsole("Critiacal error occured on .NET modules unload");
                lua.PrintToConsole(e.ToString());
            }
        }

19 Source : RetryTests.cs
with Apache License 2.0
from grpc

[Test]
        public async Task ServerStreaming_CancellatonTokenSpecified_TokenUnregisteredAndResourcesReleased()
        {
            Task FakeServerStreamCall(DataMessage request, IServerStreamWriter<DataMessage> responseStream, ServerCallContext context)
            {
                return Task.CompletedTask;
            }

            // Arrange
            var method = Fixture.DynamicGrpc.AddServerStreamingMethod<DataMessage, DataMessage>(FakeServerStreamCall);

            var serviceConfig = ServiceConfigHelpers.CreateRetryServiceConfig(retryableStatusCodes: new List<StatusCode> { StatusCode.DeadlineExceeded });
            var channel = CreateChannel(serviceConfig: serviceConfig);

            var references = new List<WeakReference>();

            // Checking that token register calls don't build up on CTS and create a memory leak.
            var cts = new CancellationTokenSource();

            // Act
            // Send calls in a different method so there is no chance that a stack reference
            // to a gRPC call is still alive after calls are complete.
            await MakeCallsAsync(channel, method, references, cts.Token).DefaultTimeout();

            // replacedert
            // There is a race when cleaning up cancellation token registry.
            // Retry a few times to ensure GC is run after unregister.
            await TestHelpers.replacedertIsTrueRetryAsync(() =>
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();

                for (var i = 0; i < references.Count; i++)
                {
                    if (references[i].IsAlive)
                    {
                        return false;
                    }
                }

                // Resources for past calls were successfully GCed.
                return true;
            }, "replacedert that retry call resources are released.");
        }

19 Source : Tool.cs
with GNU General Public License v3.0
from Guerra24

public async Task<ToolResult<R>> Execute(P @params, int threads, IProgress<ToolProgress<T>>? progress = null)
		{
			progressFilter = new Subject<ToolProgress<T>>();
			progressFilter.Window(TimeSpan.FromMilliseconds(1000)).SelectMany(i => i.TakeLast(1)).Subscribe(p => progress?.Report(p));
			ToolResult<R> result = new ToolResult<R> { replacedle = Platform.GetLocalizedString("Tools/GenericTool/Error") };
			try
			{
				result = await Process(@params, threads);
			}
			catch (Exception e)
			{
				Crashes.TrackError(e);
			}
			GC.Collect();
			GC.WaitForPendingFinalizers();
			GC.Collect();
			progressFilter.OnCompleted();
			return result;
		}

See More Examples