public void Ctor_Dispose_Success(int sizeInMegabytes) { var memoryFailPoint = new MemoryFailPoint(sizeInMegabytes); memoryFailPoint.Dispose(); memoryFailPoint.Dispose(); }
static void Main(string[] args) { int chunkSize = int.Parse(args.FirstOrDefault() ?? "32") * Megabyte; Console.WriteLine("Chunk Size: {0}", chunkSize); byte[][] hole = new byte[Terabyte / chunkSize][]; byte[] memoryPattern = Enumerable.Range(0, chunkSize).Select(o => (byte)o).ToArray(); try { for (long i = 0; i < hole.Length; i++) { // 2x chunk size should be plenty of buffer using (var check = new MemoryFailPoint(chunkSize * 2 / Megabyte)) { hole[i] = new byte[chunkSize]; Array.Copy(memoryPattern, hole[i], chunkSize); Console.WriteLine("Memory wasted {0} bytes", i * chunkSize); } } Console.WriteLine("How much memory do you have?!"); } catch (InsufficientMemoryException) { Console.WriteLine("Ran out of memory and failed gracefully. This is a success."); } }
public virtual bool IsSpaceAvailable(int sizeInMb) { if (sizeInMb < 1) { return(true); } bool isAvailable = true; MemoryFailPoint _memoryFailPoint = null; try { _memoryFailPoint = new MemoryFailPoint(sizeInMb); } catch (InsufficientMemoryException) { isAvailable = false; } catch (NotImplementedException) { _logger.Warn("MemoryFailPoint is not implemented on this platform. The MemoryManager.IsSpaceAvailable() will just return true."); } finally { if (_memoryFailPoint != null) { _memoryFailPoint.Dispose(); } } return(isAvailable); }
private void MemoryPressureLoop() { if (Runtime.Framework != Runtime.FrameworkType.DotNET) { return; } for (;;) { if (DrawState.TriggerGC) { Thread.Sleep(128); continue; } lock (CollectLock) { try { using var _ = new MemoryFailPoint(Config.RequiredFreeMemory); Thread.Sleep(128); } catch (InsufficientMemoryException) { Debug.WarningLn($"Less than {(Config.RequiredFreeMemory * 1024 * 1024).AsDataSize(decimals: 0)} available for block allocation, forcing full garbage collection"); MTexture2D.PurgeDataCache(); DrawState.TriggerGC = true; Thread.Sleep(10000); } } } }
public void Test_MemoryFailPoint() { this.SkipTestOnLinux(); // neat little class never new existed (near bottom) // http://msdn.microsoft.com/en-us/magazine/cc163716.aspx using var mem = new MemoryFailPoint(1024 * 1024 * 1024); }
public (Queue <TNode>, int) Run(TState state, TNode node, TMetric alfa, TMetric beta, int maxDepth, CancellationToken ct) { var depth = 0; var result = new Queue <TNode>(); MemoryFailPoint mfp = null; try { while (!ct.IsCancellationRequested) { if (depth > maxDepth) { break; } if (depth != 0) { mfp = new MemoryFailPoint(_search.EstimateRequiredMemoryUsageIncrementInMb(depth - 1, depth)); } _search.Search(node, depth, alfa, beta, state, ct); result.Clear(); var nextNode = node.BestChild; while (nextNode != null) { result.Enqueue(nextNode); if (nextNode.IsMaxPlayer != node.IsMaxPlayer) { break; } nextNode = nextNode.BestChild; } mfp?.Dispose(); ClearTree(node); depth++; } } catch (InsufficientMemoryException) { } catch (OperationCanceledException) { } finally { mfp?.Dispose(); } return(result, depth); }
public static void MemoryFailPointTestNoThrow() { MemoryFailPoint memFailPoint = null; memFailPoint = new MemoryFailPoint(1); memFailPoint.Dispose(); memFailPoint = new MemoryFailPoint(2); memFailPoint.Dispose(); }
private static void Main(string[] args) { using (var mf = new MemoryFailPoint(2000)) // insufficient memory exception -> jelez, ha nincs elég memória, pl. egy algoritmus indulásakor { System.Console.WriteLine("Algorithm running"); } Console.ReadLine(); }
static void Main() { Console.WriteLine("Attempts to allocate more than 2 GB of memory across worker threads."); int memUsageInMB = EstimateMemoryUsageInMB(); // For a production application consider using the threadpool instead. Thread[] threads = new Thread[numWorkItems]; // Create a work queue to be processed by multiple threads. int n = 0; for (n = 0; n < numWorkItems; n++) { workQueue.Enqueue(n); } // Continue to launch threads until the work queue is empty. while (workQueue.Count > 0) { Console.WriteLine(" GC heap (live + garbage): {0} MB", GC.GetTotalMemory(false) >> 20); MemoryFailPoint memFailPoint = null; try { // Check for available memory. memFailPoint = new MemoryFailPoint(memUsageInMB); n = (int)workQueue.Dequeue(); threads[n] = new Thread(new ParameterizedThreadStart(ThreadMethod)); WorkerState state = new WorkerState(n, memFailPoint); threads[n].Start(state); Thread.Sleep(10); } catch (InsufficientMemoryException e) { // MemoryFailPoint threw an exception, handle by sleeping for a while, then // continue processing the queue. Console.WriteLine("Expected InsufficientMemoryException thrown. Message: " + e.Message); // We could optionally sleep until a running worker thread // has finished, like this: threads[joinCount++].Join(); Thread.Sleep(1000); } } Console.WriteLine("WorkQueue is empty - blocking to ensure all threads quit (each thread sleeps for 10 seconds)"); foreach (Thread t in threads) { t.Join(); } Console.WriteLine("All worker threads are finished - exiting application."); }
private static bool IsMemoryPressured() { try { var RequiredMemory = (Config.RequiredFreeMemory * 1.5).NearestInt(); using var _ = new MemoryFailPoint(RequiredMemory); return(false); } catch (Exception ex) when(ex is InsufficientMemoryException) { return(true); } catch (Exception ex) { // I'm not sure how we'd get here. ex.PrintWarning(); return(false); } }
public CorrelationMatrix Deserialize(System.IO.Stream serializationStream) { CorrelationMatrix result = new CorrelationMatrix(); using (BinaryReader bw = new BinaryReader(serializationStream)) { string stringKey; int intValue; int intValue2; double doubleValue; double doubleKey; intValue = bw.ReadInt32(); intValue2 = bw.ReadInt32(); try { //checking for 1GB of memory availability using (MemoryFailPoint memoryFailPoint = new MemoryFailPoint(4000)) { result = new CorrelationMatrix(intValue, intValue2); //perform memory consuming operation } } catch (InsufficientMemoryException exception) { Logger.Log("Not sufficient memory. ex:" + exception); //This happens when there is not enough memory } while ((stringKey = bw.ReadString()) != "0000") { intValue = bw.ReadInt32(); intValue2 = bw.ReadInt32(); result.WordsMetadata[stringKey] = new WordMetadata { Index = intValue, Occurances = intValue2 }; } while ((doubleKey = bw.ReadDouble()) != -1) { doubleValue = bw.ReadDouble(); result.Matrix[doubleKey] = doubleValue; } } return(result); }
private static void ForceCollect(int size) { try { using (var memFailPoint = new MemoryFailPoint(size)) { } } catch (InsufficientMemoryException) { //throw; } catch (OutOfMemoryException) { } finally { GC.Collect(); GC.WaitForPendingFinalizers(); } }
/** -------------------------------------------------------------------- **/ public static Boolean MemoryGuard(int RequiredMegabytes) { GC.Collect(); if (MacroscopePreferencesManager.GetEnableMemoryGuard()) { MemoryFailPoint MemGate = null; try { DebugMsg(string.Format("RequiredMegabytes: {0}", RequiredMegabytes), true); MemGate = new MemoryFailPoint(RequiredMegabytes); } catch (InsufficientMemoryException ex) { if (ThrowInsufficientMemoryException) { throw new MacroscopeInsufficientMemoryException( message: string.Format("Insufficient memory available: {0}MB is required", RequiredMegabytes), innerException: ex ); } } GC.Collect(); if (MemGate != null) { return(true); } return(false); } return(true); }
internal WorkerState(int threadNumber, MemoryFailPoint memoryFailPoint) { _threadNumber = threadNumber; _memFailPoint = memoryFailPoint; }
private void RecorderController_Load(object sender, EventArgs e) { //test each codec recording //VideoCaptureController.SaveTestCodecFiles(); return; // Application.ApplicationExit += new EventHandler(Application_ApplicationExit); ////VideoCaptureController capturer = new VideoCaptureController(); // System.Timers.Timer timerResetCheckOrNot = new System.Timers.Timer(3500); string sLastDatabaseOrCSVGadacemaName = ""; timerResetCheckOrNot.Elapsed += delegate(object senderTimer, ElapsedEventArgs eTimer) { if ((DateTime.Now.Hour >= 3) && (DateTime.Now.Hour < 7)) { //don't record between 03:00 AM and 07:00 AM VideoCaptureController.StopRecording(); return; } string sAxaliGadacemisSaxeli; DateTime dtAxaliGadacemisDackebisDro; DateTime dtAxaliGadacemisDamtavrebisDro = DateTime.Now;//assign dummy if (true == nextCSVResult(out sAxaliGadacemisSaxeli, out dtAxaliGadacemisDackebisDro) && false == (dtAxaliGadacemisDackebisDro.Hour < 4 && DateTime.Now.Hour >= 7) &&//dont record last night's shows when now is morning false == fMidisDatabasedanChacera) { // string sGadacemaName = (0 < sAxaliGadacemisSaxeli.IndexOf("_")) ? sAxaliGadacemisSaxeli.Substring(0, sAxaliGadacemisSaxeli.IndexOf("_")) //:"undefined"; : (0 < sAxaliGadacemisSaxeli.IndexOf(".")) ? sAxaliGadacemisSaxeli.Substring(0, sAxaliGadacemisSaxeli.LastIndexOf(".")) : sAxaliGadacemisSaxeli; ChangeParamIfInDBIsGadacemaOnlyForName(ref sGadacemaName); sLastDatabaseOrCSVGadacemaName = sGadacemaName; //call capture VideoCaptureController.StartRecording(sPrepareAndReturnFileDestination(sGadacemaName, dtAxaliGadacemisDackebisDro)); // fDilasAvtomaturiChacera = false; fMidisDatabasedanChacera = false; // } else if (true == isThereGadacemebiForNow(sGadacemisSaxeliLastTime, out sAxaliGadacemisSaxeli, out dtAxaliGadacemisDackebisDro, out dtAxaliGadacemisDamtavrebisDro) && sLastDatabaseOrCSVGadacemaName != sAxaliGadacemisSaxeli) { // //string sGadacemaName = (0 < sAxaliGadacemisSaxeli.IndexOf("_")) // ? sAxaliGadacemisSaxeli.Substring(0, sAxaliGadacemisSaxeli.IndexOf("_")) // //:"undefined"; // : sAxaliGadacemisSaxeli.Substring(0, sAxaliGadacemisSaxeli.LastIndexOf(".")).Replace(" ", ""); string sGadacemaName = sAxaliGadacemisSaxeli; sLastDatabaseOrCSVGadacemaName = sGadacemaName; //call capture VideoCaptureController.StartRecording(sPrepareAndReturnFileDestination(sGadacemaName, dtAxaliGadacemisDackebisDro)); // fDilasAvtomaturiChacera = false; fMidisDatabasedanChacera = true; // } else { //tu am cutas vicert database-dan da dro gauvida, gavacherot if (true == fMidisDatabasedanChacera && DateTime.Now >= dtAxaliGadacemisDamtavrebisDro) { VideoCaptureController.StopRecording(); fDilasAvtomaturiChacera = false; fMidisDatabasedanChacera = false; } else { //yoveltvis ganaaxlos chacera, roca naxavs ro gacherebulia if (false == (true == fMidisDatabasedanChacera && DateTime.Now < dtAxaliGadacemisDamtavrebisDro)) { //if it's between 7:00AM and 8:00AM and the program has already started automated recording if (VideoCaptureController.fIsRecording()) { //TODO: or predict memory scarciness with MemoryFailPoint Class try { MemoryFailPoint mfp = new MemoryFailPoint(500); } catch (InsufficientMemoryException) { //VideoCaptureController.StartRecording(sPrepareAndReturnFileDestination(sLastDatabaseOrCSVGadacemaName, DateTime.Now)); } // if (GetFreeMemory() < 500) { Console.WriteLine("Low Memory: {0} Megabytes. Restarting recording. ", GetFreeMemory()); VideoCaptureController.StartRecording(sPrepareAndReturnFileDestination(sLastDatabaseOrCSVGadacemaName, DateTime.Now)); dtAxaliGadacemisDackebisDro = DateTime.Now; } else { //tu dilit avtomaturi chaceraa chartuli da ert saatze metia chacerili, gackvitos chacera da tavidan daickos if ( (true == fDilasAvtomaturiChacera) && DateTime.Now.Subtract(dtLastAvtomaturiChacerisDro).Minutes > 30 || /////////////////////////// !!!!!!!!!!!: always split to 30 minute files instead of only at morning DateTime.Now.Subtract(dtAxaliGadacemisDackebisDro).Minutes > 30 ) { //stop & start recording VideoCaptureController.StartRecording(sPrepareAndReturnFileDestination("autorecording", DateTime.Now)); dtAxaliGadacemisDackebisDro = DateTime.Now; fDilasAvtomaturiChacera = true; fMidisDatabasedanChacera = false; dtLastAvtomaturiChacerisDro = DateTime.Now; Console.WriteLine("Avtomaturma chaceram daimaxsovra ertsaatiani faili da agrdzelebs shemdegis chaceras."); } } } //AXALI: roca gacherebulia da csv/db-shi axali chanaceri ar aris else { //stop & start recording VideoCaptureController.StartRecording(sPrepareAndReturnFileDestination("autorecording", DateTime.Now)); dtAxaliGadacemisDackebisDro = DateTime.Now; fDilasAvtomaturiChacera = true; fMidisDatabasedanChacera = false; dtLastAvtomaturiChacerisDro = DateTime.Now; Console.WriteLine("Vrtavt chaceras avtomaturad. "); } // } else { Console.WriteLine("{0}, ar vicert avtomaturad imitom rom bazidan midis chacera. ", DateTime.Now); } } } }; timerResetCheckOrNot.Start(); // sqlConn.Open(); // txtPathToCSV.Text = File.ReadAllText(VideoCaptureController.sFileContainingInfoAboutCSVFilePath); // }
static void AllocBigMemoryBlock2(int pass) { const int MB = 1024 * 1024; byte[] array = null; long maxMem = 0; int arraySize = 0; MemoryFailPoint memFailPoint; while (Console.KeyAvailable == false) { try { arraySize += 10; using (memFailPoint = new MemoryFailPoint(arraySize)) { array = new byte[arraySize * MB]; array[arraySize * MB - 1] = 100; maxMem = GC.GetTotalMemory(true); Console.Write("Pass:{0} " + "Max Array Size (MB): {1:D4} {2:D4}\r", pass, arraySize, Convert.ToInt32(maxMem / MB)); } } catch (InsufficientMemoryException) { Console.Write("\n insufficient memory exception"); Console.Write("\n"); maxMem = GC.GetTotalMemory(true); if (arraySize < 20) { Console.Write("Pass:{0} Small Array" + " Size (MB): {1:D4} {2:D4} {3}\r\n\n", pass, arraySize, Convert.ToInt32(maxMem / MB), "Insufficient Memory..."); } else { Console.Write("Pass:{0} Failed Array Size" + " (MB): {1:D4} {2:D4} {3}\r\n\n", pass, arraySize, Convert.ToInt32(maxMem / MB), "Out Of Memory..."); } break; } catch (OutOfMemoryException) { Console.Write("\n outof memory exception"); Console.Write("\n"); maxMem = GC.GetTotalMemory(true); if (arraySize < 20) { Console.Write("Pass:{0} Small Array" + " Size (MB): {1:D4} {2:D4} {3}\r\n\n", pass, arraySize, Convert.ToInt32(maxMem / MB), "Insufficient Memory..."); } else { Console.Write("Pass:{0} Failed Array" + " Size (MB): {1:D4} {2:D4} {3}\r\n\n", pass, arraySize, Convert.ToInt32(maxMem / MB), "Out Of Memory..."); } break; } finally { array = null; GC.Collect(); GC.WaitForPendingFinalizers(); } } }