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
19
Source : ThroughputToFileBench.cs
with MIT License
from Abc-Arbitrage
with MIT License
from Abc-Arbitrage
public static void Run()
{
var dir = Path.GetFullPath(Guid.NewGuid().ToString());
Directory.CreateDirectory(dir);
try
{
Console.WriteLine("Initializing...");
BasicConfigurator.Configure(
new ZeroLogBasicConfiguration
{
Appenders = { new DateAndSizeRollingFileAppender(Path.Combine(dir, "Output")), },
LogEventQueueSize = 1000 * 4096 * 4,
LogEventPoolExhaustionStrategy = LogEventPoolExhaustionStrategy.WaitForLogEvent
}
);
var log = LogManager.GetLogger(typeof(ThroughputToFileBench));
var duration = TimeSpan.FromSeconds(10);
Console.WriteLine("Starting...");
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
var sw = Stopwatch.StartNew();
long counter = 0;
while (sw.Elapsed < duration)
{
counter++;
log.Debug().Append("Counter is: ").Append(counter).Log();
}
Console.WriteLine($"Log events: {counter:N0}, Time to append: {sw.Elapsed}");
Console.WriteLine("Flushing...");
LogManager.Shutdown();
Console.WriteLine($"Time to flush: {sw.Elapsed}");
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
finally
{
Directory.Delete(dir, true);
}
Console.WriteLine("Done");
}
19
Source : SimpleLatencyBenchmark.cs
with MIT License
from Abc-Arbitrage
with MIT License
from Abc-Arbitrage
public static SimpleLatencyBenchmarkResult RunBench(int producingThreadCount, Func<HistogramBase> produce, ManualResetEventSlim signal)
{
var tasks = Enumerable.Range(0, producingThreadCount).Select(_ => new Task<HistogramBase>(produce, TaskCreationOptions.LongRunning)).ToList();
GC.Collect(2);
GC.WaitForPendingFinalizers();
GC.Collect(2);
var collectionsBefore = GC.CollectionCount(0);
foreach (var task in tasks)
{
task.Start();
}
signal.Wait(TimeSpan.FromSeconds(30));
var collectionsAfter = GC.CollectionCount(0);
var result = new SimpleLatencyBenchmarkResult { ExecutionTimes = tasks.Select(x => x.Result).ToList(), CollectionCount = collectionsAfter - collectionsBefore };
return result;
}
19
Source : Navigator.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public void GoBack()
{
var lastExampleView = _currentExample;
_history.Undo();
if (_history.Current is Example example)
{
Navigate(example);
ServiceLocator.Container.Resolve<IModule>().CurrentExample = example;
}
else
{
Navigate((Guid)_history.Current);
}
ServiceLocator.Container.Resolve<IExampleViewModel>().BreadCrumbViewModel.IsShowingBreadcrumbNavigation = false;
ServiceLocator.Container.Resolve<IExampleViewModel>().ExportExampleViewModel.IsExportVisible = false;
GoBackCommand.RaiseCanExecuteChanged();
GoForwardCommand.RaiseCanExecuteChanged();
NavigateToHomeCommand.RaiseCanExecuteChanged();
if (CurrentExample is ExampleAppPage lastExamplePage)
{
// Required to release memory from last example
lastExamplePage.ViewModel = null;
}
if (lastExampleView != null)
{
lastExampleView.View = null;
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
19
Source : Navigator.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public void GoForward()
{
var lastExampleView = _currentExample;
_history.Redo();
if (_history.Current is Example example)
{
Navigate(example);
ServiceLocator.Container.Resolve<IModule>().CurrentExample = example;
}
else
{
Navigate((Guid)_history.Current);
}
ServiceLocator.Container.Resolve<IExampleViewModel>().ExportExampleViewModel.IsExportVisible = false;
ServiceLocator.Container.Resolve<IExampleViewModel>().BreadCrumbViewModel.IsShowingBreadcrumbNavigation = false;
GoBackCommand.RaiseCanExecuteChanged();
GoForwardCommand.RaiseCanExecuteChanged();
NavigateToHomeCommand.RaiseCanExecuteChanged();
if (CurrentExample is ExampleAppPage lastExamplePage)
{
// Required to release memory from last example
lastExamplePage.ViewModel = null;
}
if (lastExampleView != null)
{
lastExampleView.View = null;
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
19
Source : Navigator.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private void OnExamplesFrameBeforeNavigation()
{
if (_currentExample != null)
{
_currentExample.View = null;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
}
19
Source : Navigator.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private void GoToHome()
{
var lastExampleView = _currentExample;
Instance.Navigate(AppPage.HomePageId);
_history.Push(AppPage.HomePageId);
ServiceLocator.Container.Resolve<IExampleViewModel>().BreadCrumbViewModel.IsShowingBreadcrumbNavigation = false;
ServiceLocator.Container.Resolve<IExampleViewModel>().ExportExampleViewModel.IsExportVisible = false;
ServiceLocator.Container.Resolve<IMainWindowViewModel>().HideSearchCommand.Execute(null);
// Clears memory on going to home
((TransitioningFrame)_examplesFrame.Frame).SetContentNull();
if (CurrentExample is ExampleAppPage lastExamplePage)
{
// Required to release memory from last example
lastExamplePage.ViewModel = null;
}
if (lastExampleView != null)
{
lastExampleView.View = null;
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
19
Source : TestCase.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public void Run(Action<double> completed)
{
//Arction added memory garbage collecting
GC.Collect();
GC.WaitForPendingFinalizers();
_speedTest.Execute(_args, _duration, completed);
}
19
Source : MainViewModel.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private void TestFinished(TestCase testCase, double result)
{
testCase.Dispose();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
RunNextTest();
}
19
Source : Map.cs
with GNU General Public License v3.0
from AHeroicLlama
with GNU General Public License v3.0
from AHeroicLlama
public static void Reset()
{
SettingsMap.brightness = SettingsMap.brightnessDefault;
SettingsMap.layerMilitary = false;
SettingsMap.grayScale = false;
DrawBaseLayer();
GC.Collect();
GC.WaitForPendingFinalizers();
}
19
Source : GarbageCollectionSample.cs
with The Unlicense
from ahotko
with The Unlicense
from ahotko
private void ForceGarbageCollection()
{
var gc = new GarbageCollection();
var gcBefore = new GarbageCollectionInfo();
Console.WriteLine($"Before Garbage Collection: {gcBefore}");
gc.MakeSomeGarbage();
var gcAfterGeneratingGarbage = new GarbageCollectionInfo();
Console.WriteLine($"After Generating Garbage: {gcAfterGeneratingGarbage}");
GC.Collect(0);
var gcAfterCleanupGen0 = new GarbageCollectionInfo();
Console.WriteLine($"After Garbage Collection of Gen0: {gcAfterCleanupGen0}");
GC.Collect(1);
var gcAfterCleanupGen1 = new GarbageCollectionInfo();
Console.WriteLine($"After Garbage Collection of Gen1: {gcAfterCleanupGen1}");
GC.WaitForPendingFinalizers();
GC.Collect(2);
var gcAfterCleanupGen2 = new GarbageCollectionInfo();
Console.WriteLine($"After Garbage Collection of Gen2: {gcAfterCleanupGen2}");
GC.WaitForPendingFinalizers();
GC.Collect();
var gcAfterCleanup = new GarbageCollectionInfo();
Console.WriteLine($"After Garbage Collection: {gcAfterCleanup}");
}
19
Source : Program.cs
with MIT License
from Alan-FGR
with MIT License
from Alan-FGR
static void Tests2()
{
foreach (var warmup in new[] { true, false })
for (int li = 0; li < 140; li++)
{
GC.Collect();
GC.WaitForPendingFinalizers();
var uts = new UntypedBase[16];
for (int i = 0; i < 16; i++)
{
if(i % 2 == 0)
uts[i] = new Typed1();
else
uts[i] = new Typed2();
}
var its = new ISum[16];
for (int i = 0; i < 16; i++)
{
if (i % 2 == 0)
its[i] = new Typed1();
else
its[i] = new Typed2();
}
var dts = new NoVirt[16];
for (int i = 0; i < 16; i++)
{
if (i % 2 == 0)
dts[i] = new NoVirt();
else
dts[i] = new NoVirt();
}
Measure($"Interface", warmup, () =>
{
int check = 0;
for (int i = 0; i < 1 << 20; i++)
check += its[i % 16].Sum();
return check;
});
Measure($"Cast", warmup, () =>
{
int check = 0;
for (int i = 0; i < 1 << 20; i++)
check += uts[i % 16].CastSum();
return check;
});
Measure($"Uncast", warmup, () =>
{
int check = 0;
for (int i = 0; i < 1 << 20; i++)
check += uts[i % 16].Sum();
return check;
});
Measure($"Decast", warmup, () =>
{
int check = 0;
for (int i = 0; i < 1 << 20; i++)
check += uts[i % 16].Sum();
return check;
});
Measure($"Devirt", warmup, () =>
{
int check = 0;
for (int i = 0; i < 1 << 20; i++)
check += dts[i % 16].Sum();
return check;
});
}
foreach (var result in results_)
{
Console.WriteLine(
$"Benchmarked avg of {result.Value.Count} samples totalling {result.Value.Average():F3} µs to {result.Key}");
}
}
19
Source : Program.cs
with MIT License
from Alan-FGR
with MIT License
from Alan-FGR
private static void Tests1()
{
int keysCount = 1 << 15;
int maxValue = 1 << 16;
uint umaxValue = 1 << 16;
int[] keys = new int[keysCount];
uint[] ukeys = new uint[keysCount];
var r = new Random(42);
for (int i = 0; i < keysCount; i++)
{
keys[i] = r.Next(maxValue);
ukeys[i] = (uint) keys[i];
}
foreach (var warmup in new[] {true, false})
for (int li = 0; li < 40; li++)
{
GC.Collect();
GC.WaitForPendingFinalizers();
var dict = new Dictionary<int, int>();
Measure($"Add to Dictionary", warmup, () =>
{
for (int i = 0; i < keysCount; i++)
dict[keys[i]] = maxValue - keys[i];
return 0;
});
Measure($"Sum in Dictionary", warmup, () =>
{
int checksum = 0;
for (int i = 0; i < keysCount; i++)
checksum += dict[keys[i]];
return checksum;
});
Measure($"Rem from Dictionary", warmup, () =>
{
for (int i = 0; i < keysCount; i++)
dict.Remove(keys[i]);
return 0;
});
var sa = new SparseArray(16, 10);
Measure($"Add to SparseArray", warmup, () =>
{
for (int i = 0; i < keysCount; i++)
sa.Add(keys[i], maxValue - keys[i]);
return 0;
});
Measure($"Sum in SparseArray", warmup, () =>
{
int checksum = 0;
for (int i = 0; i < keysCount; i++)
checksum += sa.Get(keys[i]);
return checksum;
});
//Measure($"Rem from SparseArray", warmup, () =>
//{
// for (int i = 0; i < keysCount; i++)
// dict.Remove(keys[i]);
// return 0;
//});
var um = new UInt32UInt32Map();
Measure($"Add to UInt32UInt32Map", warmup, () =>
{
for (int i = 0; i < keysCount; i++)
um.GetRef(ukeys[i]) = (umaxValue - ukeys[i]);
return 0;
});
Measure($"Sum in UInt32UInt32Map", warmup, () =>
{
uint checksum = 0;
for (int i = 0; i < keysCount; i++)
checksum += um.GetRef(ukeys[i]);
return checksum;
});
var im = new Int32Int32Map();
Measure($"Add to Int32Int32Map", warmup, () =>
{
for (int i = 0; i < keysCount; i++)
im.GetRef(keys[i]) = (maxValue - keys[i]);
return 0;
});
Measure($"Sum in Int32Int32Map", warmup, () =>
{
int checksum = 0;
for (int i = 0; i < keysCount; i++)
checksum += im.GetRef(keys[i]);
return checksum;
});
/*
var pool = new BufferPool(256).SpecializeFor<int>();
QuickDictionary<int, int, Buffer<int>, Buffer<int>, Buffer<int>, PrimitiveComparer<int>>
.Create(pool, pool, pool, 2, 3, out var bdict);
Measure($"Add to BepuDictionary", warmup, () =>
{
for (int i = 0; i < keysCount; i++)
bdict.Add(keys[i], maxValue - keys[i], pool, pool, pool);
return 0;
});
Measure($"Sum in BepuDictionary", warmup, () =>
{
int checksum = 0;
for (int i = 0; i < keysCount; i++)
{
bdict.TryGetValue(keys[i], out int value);
checksum += value;
}
return checksum;
});
Measure($"Rem from BepuDictionary", warmup, () =>
{
for (int i = 0; i < keysCount; i++)
bdict.FastRemove(keys[i]);
return 0;
});
//dictionary.EnsureCapacity(dictionary.Count * 3, pool, pool, pool);
//dictionary.Compact(pool, pool, pool);
bdict.Dispose(pool, pool, pool);
pool.Raw.Clear();
*/
}
foreach (var result in results_)
{
Console.WriteLine(
$"Benchmarked avg of {result.Value.Count} samples totalling {result.Value.Average():F3} µs to {result.Key}");
}
//TestSetResizing<Buffer<int>, BufferPool<int>>(bufferPool);
//var arrayPool = new ArrayPool<int>();
//TestSetResizing<Array<int>, ArrayPool<int>>(arrayPool);
//arrayPool.Clear();
}
19
Source : OptimizerExecutor.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
private async void PrimeThreadWorkerPlace()
{
ReportsToFazes = new List<OptimazerFazeReport>();
int countBots = BotCountOneFaze();
SendLogMessage(OsLocalization.Optimizer.Message4 + countBots, LogMessageType.System);
DateTime timeStart = DateTime.Now;
_countAllServersMax = countBots;
for (int i = 0; i < _master.Fazes.Count; i++)
{
if (_neadToStop)
{
_primeThreadWorker = null;
TestReadyEvent?.Invoke(ReportsToFazes);
return;
}
if (_master.Fazes[i].TypeFaze == OptimizerFazeType.InSample)
{
OptimazerFazeReport report = new OptimazerFazeReport();
report.Faze = _master.Fazes[i];
ReportsToFazes.Add(report);
StartAsuncBotFactoryInSample(countBots, _master.StrategyName, _master.IsScript, "InSample");
StartOptimazeFazeInSample(_master.Fazes[i], report, _parameters, _parametersOn);
}
else
{
SendLogMessage("ReportsCount" + ReportsToFazes[ReportsToFazes.Count - 1].Reports.Count.ToString(), LogMessageType.System);
OptimazerFazeReport reportFiltred = new OptimazerFazeReport();
EndOfFazeFiltration(ReportsToFazes[ReportsToFazes.Count - 1], reportFiltred);
OptimazerFazeReport report = new OptimazerFazeReport();
report.Faze = _master.Fazes[i];
ReportsToFazes.Add(report);
StartAsuncBotFactoryOutOfSample(reportFiltred, _master.StrategyName, _master.IsScript, "OutOfSample");
StartOptimazeFazeOutOfSample(report, reportFiltred);
}
GC.Collect();
GC.WaitForPendingFinalizers();
}
TimeSpan time = DateTime.Now - timeStart;
SendLogMessage(OsLocalization.Optimizer.Message7, LogMessageType.System);
SendLogMessage("Total test time = " + time.ToString(), LogMessageType.System);
TestReadyEvent?.Invoke(ReportsToFazes);
_primeThreadWorker = null;
return;
}
19
Source : FileProcessingManager.cs
with MIT License
from Analogy-LogViewer
with MIT License
from Analogy-LogViewer
public void Reset()
{
ProcessedFileNames.Clear();
Messages.Clear();
GC.Collect();
GC.WaitForPendingFinalizers();
}
19
Source : SimpleBenchmarkRunner.cs
with Apache License 2.0
from AppMetrics
with Apache License 2.0
from AppMetrics
private static void PerformCollection()
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
Thread.Sleep(200);
}
19
Source : Utils.cs
with MIT License
from arsium
with MIT License
from arsium
public static void ClearMem()
{
GC.Collect();
GC.WaitForPendingFinalizers();
SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, -1, -1);
EmptyWorkingSet(Process.GetCurrentProcess().Handle);
}
19
Source : Startup.xaml.cs
with Apache License 2.0
from ascora
with Apache License 2.0
from ascora
private void Button_Click(object sender, RoutedEventArgs e)
{
var window = new MainWindow();
window.ShowDialog();
GC.Collect();
GC.WaitForPendingFinalizers();
}
19
Source : DefaultHttpClientFactoryTest.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public async Task Factory_CleanupCycle_DisposesEligibleHandler()
{
// Arrange
var disposeHandler = new DisposeTrackingHandler();
Options.Get("github").HttpMessageHandlerBuilderActions.Add(b =>
{
b.AdditionalHandlers.Add(disposeHandler);
});
var factory = new TestHttpClientFactory(Services, ScopeFactory, LoggerFactory, Options, EmptyFilters)
{
EnableExpiryTimer = true,
EnableCleanupTimer = true,
};
var cleanupEntry = await SimulateClientUse_Factory_CleanupCycle_DisposesEligibleHandler(factory);
// Being pretty conservative here because we want this test to be reliable,
// and it depends on the GC and timing.
for (var i = 0; i < 3; i++)
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
if (cleanupEntry.CanDispose)
{
break;
}
await Task.Delay(TimeSpan.FromSeconds(1));
}
replacedert.True(cleanupEntry.CanDispose, "Cleanup entry disposable");
// Act
factory.CleanupTimer_Tick();
// replacedert
replacedert.Empty(factory._expiredHandlers);
replacedert.Equal(1, disposeHandler.DisposeCount);
replacedert.False(factory.CleanupTimerStarted.IsSet, "Cleanup timer not started");
}
19
Source : DefaultHttpClientFactoryTest.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public async Task Factory_CleanupCycle_DisposesLiveHandler()
{
// Arrange
var disposeHandler = new DisposeTrackingHandler();
Options.Get("github").HttpMessageHandlerBuilderActions.Add(b =>
{
b.AdditionalHandlers.Add(disposeHandler);
});
var factory = new TestHttpClientFactory(Services, ScopeFactory, LoggerFactory, Options, EmptyFilters)
{
EnableExpiryTimer = true,
EnableCleanupTimer = true,
};
var cleanupEntry = await SimulateClientUse_Factory_CleanupCycle_DisposesLiveHandler(factory, disposeHandler);
// Being pretty conservative here because we want this test to be reliable,
// and it depends on the GC and timing.
for (var i = 0; i < 3; i++)
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
if (cleanupEntry.CanDispose)
{
break;
}
await Task.Delay(TimeSpan.FromSeconds(1));
}
replacedert.True(cleanupEntry.CanDispose, "Cleanup entry disposable");
// Act - 2
factory.CleanupTimer_Tick();
// replacedert
replacedert.Empty(factory._expiredHandlers);
replacedert.Equal(1, disposeHandler.DisposeCount);
replacedert.False(factory.CleanupTimerStarted.IsSet, "Cleanup timer not started");
}
19
Source : GISBase.cs
with MIT License
from aspose-gis
with MIT License
from aspose-gis
protected Response Process(string modelName, string fileName, string folderName, string outFileExtension, bool createZip, bool checkNumberofPages, string methodName, ActionDelegate action,
bool deleteSourceFolder = true, string zipFileName = null)
{
string guid = Guid.NewGuid().ToString();
string outFolder = "";
string sourceFolder = Config.Configuration.WorkingDirectory + folderName;
fileName = sourceFolder + "\\" + fileName;
string fileExtension = Path.GetExtension(fileName).ToLower();
string outfileName = Path.GetFileNameWithoutExtension(fileName) + outFileExtension;
string outPath = "";
string zipOutFolder = Config.Configuration.OutputDirectory + guid;
string zipOutfileName, zipOutPath;
if (string.IsNullOrEmpty(zipFileName))
{
zipOutfileName = guid + ".zip";
zipOutPath = Config.Configuration.OutputDirectory + zipOutfileName;
}
else
{
var guid2 = Guid.NewGuid().ToString();
outFolder = guid2;
zipOutfileName = zipFileName + ".zip";
zipOutPath = Config.Configuration.OutputDirectory + guid2;
Directory.CreateDirectory(zipOutPath);
zipOutPath += "/" + zipOutfileName;
}
if (createZip)
{
outfileName = Path.GetFileNameWithoutExtension(fileName) + outFileExtension;
outPath = zipOutFolder + "/" + outfileName;
Directory.CreateDirectory(zipOutFolder);
}
else
{
outFolder = guid;
outPath = Config.Configuration.OutputDirectory + outFolder;
Directory.CreateDirectory(outPath);
outPath += "/" + outfileName;
}
string statusValue = "OK";
int statusCodeValue = 200;
try
{
action(fileName, outPath, zipOutFolder);
if (createZip)
{
ZipFile.CreateFromDirectory(zipOutFolder, zipOutPath);
Directory.Delete(zipOutFolder, true);
outfileName = zipOutfileName;
}
if (deleteSourceFolder)
{
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
Directory.Delete(sourceFolder, true);
}
}
catch (Exception ex)
{
statusCodeValue = 500;
statusValue = "500 " + ex.Message;
}
return new Response
{
FileName = outfileName,
FolderName = outFolder,
Status = statusValue,
StatusCode = statusCodeValue,
};
}
19
Source : ModelBase.cs
with MIT License
from aspose-pdf
with MIT License
from aspose-pdf
protected Response Process(string modelName, string fileName, string folderName, string outFileExtension, bool createZip, bool checkNumberofPages, string methodName, ActionDelegate action,
bool deleteSourceFolder = true, string zipFileName = null)
{
string guid = Guid.NewGuid().ToString();
string outFolder = "";
string sourceFolder = Aspose.Pdf.Live.Demos.UI.Config.Configuration.WorkingDirectory + folderName;
fileName = sourceFolder + "\\" + fileName;
string fileExtension = Path.GetExtension(fileName).ToLower();
// Check word file have more than one number of pages or not to create zip file
if ((checkNumberofPages) && (createZip) && (modelName == "AsposePdfConversion"))
{
Aspose.Pdf.Doreplacedent doc = new Aspose.Pdf.Doreplacedent(fileName);
createZip = doc.Pages.Count > 1;
}
string outfileName = Path.GetFileNameWithoutExtension(fileName) + outFileExtension;
string outPath = "";
string zipOutFolder = Aspose.Pdf.Live.Demos.UI.Config.Configuration.OutputDirectory + guid;
string zipOutfileName, zipOutPath;
if (string.IsNullOrEmpty(zipFileName))
{
zipOutfileName = guid + ".zip";
zipOutPath = Aspose.Pdf.Live.Demos.UI.Config.Configuration.OutputDirectory + zipOutfileName;
}
else
{
var guid2 = Guid.NewGuid().ToString();
outFolder = guid2;
zipOutfileName = zipFileName + ".zip";
zipOutPath = Aspose.Pdf.Live.Demos.UI.Config.Configuration.OutputDirectory + guid2;
if (createZip)
{
Directory.CreateDirectory(zipOutPath);
}
zipOutPath += "/" + zipOutfileName;
}
if (createZip)
{
outfileName = Path.GetFileNameWithoutExtension(fileName) + outFileExtension;
outPath = zipOutFolder + "/" + outfileName;
Directory.CreateDirectory(zipOutFolder);
}
else
{
outFolder = guid;
outPath = Aspose.Pdf.Live.Demos.UI.Config.Configuration.OutputDirectory + outFolder;
Directory.CreateDirectory(outPath);
outPath += "/" + outfileName;
}
string statusValue = "OK";
int statusCodeValue = 200;
try
{
action(fileName, outPath, zipOutFolder);
if (createZip)
{
ZipFile.CreateFromDirectory(zipOutFolder, zipOutPath);
Directory.Delete(zipOutFolder, true);
outfileName = zipOutfileName;
}
if (deleteSourceFolder)
{
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
Directory.Delete(sourceFolder, true);
}
}
catch (Exception ex)
{
statusCodeValue = 500;
statusValue = "500 " + ex.Message;
}
return new Response
{
FileName = outfileName,
FolderName = outFolder,
Status = statusValue,
StatusCode = statusCodeValue,
FileProcessingErrorCode = FileProcessingErrorCode.OK
};
}
19
Source : AddInBase.cs
with Microsoft Public License
from atrenton
with Microsoft Public License
from atrenton
protected virtual void Dispose(bool disposing)
{
if (_disposed) return;
if (disposing) // dispose of managed resources
{
Tracer.WriteTraceMethodLine();
Application = null;
COMAddIn = null;
RibbonEventHandler = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
_disposed = true;
}
19
Source : RibbonView.cs
with Microsoft Public License
from atrenton
with Microsoft Public License
from atrenton
internal void OptionsForm_Show(object sender, RibbonEventArgs e)
{
if (sender is API.AddInBase && e.Control.Tag == "OptionsForm")
{
Tracer.WriteTraceMethodLine();
var addIn = sender as API.AddInBase;
var savedTemplate = Properties.Settings.Default.PageTemplate;
using (var form = new UI.OptionsForm())
{
form.AboutIconImage_ResourceName = Component.AppIcon_ResourceName;
form.AboutText = string.Join(Environment.NewLine, new[] {
addIn.Description,
Component.replacedemblyInfo.Copyright,
$"Version {Component.replacedemblyInfo.ProductVersion}"
});
form.replacedle = $"{Component.replacedemblyInfo.replacedle} Options";
var owner = e.Control.Context as OneNote.Window;
form.ShowDialog(new Utils.WinHelper.Win32Window(owner));
}
if (Properties.Settings.Default.PageTemplate != savedTemplate)
{
_binder.Rebind(addIn.Application);
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
}
19
Source : FileWatcherTest.cs
with MIT License
from Autodesk
with MIT License
from Autodesk
[Test]
public void _watcher_DeletedTest()
{
string dirName = "TestDirectory4";
Directory d = fact_createTestDirectory(dirName);
string fname = System.IO.Path.Combine(d.Path, "Test1.txt");
File df = new File(fname);
df.Create();
FileWatcher fw = new FileWatcher(fname);
// add deleted event and test if fires when file is deleted.
_TestTrigger = new AutoResetEvent(false);
bHandlerRaised = false;
tmpFileName = "";
fw.FileDeleted += fw_FileDeleted;
df.Delete();
_TestTrigger.WaitOne(2000);
replacedert.IsTrue(bHandlerRaised, "File Deleted Event not raised");
replacedert.AreEqual(fname, tmpFileName, "Wrong File Delete Event raised");
// now prove event is not raised if file is deleted
df.Create();
fw.FileDeleted -= fw_FileDeleted; // remove event
_TestTrigger = null;
_TestTrigger = new AutoResetEvent(false);
bHandlerRaised = false;
GC.WaitForPendingFinalizers();
df.Delete();
_TestTrigger.WaitOne(2000); // should time out
replacedert.IsFalse(bHandlerRaised, "File Deleted Event should not raised");
_TestTrigger = null;
fw = null;
}
19
Source : DirectoryWatcherTest.cs
with MIT License
from Autodesk
with MIT License
from Autodesk
[Test]
public void EnableRaisingEventsTest()
{
string dirName = "testDir";
Directory directoryToWatch = fact_createTestDirectory(dirName);
DirectoryWatcher target = new DirectoryWatcher(directoryToWatch);
bHandlerRaised = false;
_TestTrigger = new AutoResetEvent(false);
File df = new File(directoryToWatch, "test1.txt");
target.FileCreated += dw_FileCreated;
target.EnableRaisingEvents = false;
df.Create();
_TestTrigger.WaitOne(3000); // should time out
replacedert.IsFalse(bHandlerRaised, "Event should not be raised");
//now prove that event is raised by recreating file.
bHandlerRaised = false;
GC.WaitForPendingFinalizers();
System.IO.File.Delete(df.Path);
target.EnableRaisingEvents = true;
df.Create();
_TestTrigger.WaitOne(3000); // should expect event
replacedert.IsTrue(bHandlerRaised, "Event should be raised");
target.FileCreated -= dw_FileCreated;
_TestTrigger = null;
}
19
Source : DirectoryWatcherTest.cs
with MIT License
from Autodesk
with MIT License
from Autodesk
[Test]
public void _watcher_DeletedTest()
{
string dirName = "DelDirTest2";
Directory mydir = fact_createTestDirectory(dirName);
string dirPath = mydir.Path;
DirectoryWatcher dw;
bHandlerRaised = false;
try
{
File df = new File(mydir, "DelFile.txt");
df.Create();
dw = new DirectoryWatcher(mydir, "delFile.txt", false);
dw.EnableRaisingEvents = false;
dw.FileDeleted += dw_FileDeleted;
dw.EnableRaisingEvents = true;
_TestTrigger = new AutoResetEvent(false);
GC.WaitForPendingFinalizers();
df.Delete(); // should raise trigger
_TestTrigger.WaitOne(5000);
// test for del
replacedert.IsTrue(bHandlerRaised, "Handler not raised");
bHandlerRaised = false;
//Test that delete of different file type should not be raised.
File df2 = new File(mydir, "DelFile.log");
df2.Create();
df2.Delete();
_TestTrigger.WaitOne(2000);
replacedert.IsFalse(bHandlerRaised, "No Event should be raised");
//now check what happens if directory is deleted
dw.DirectoryUnavailableTimerStatus = true;
replacedert.IsTrue(dw.DirectoryUnavailableTimerStatus, "Timer should be enabled");
bHandlerRaised = false;
// dw.FileDeleted -= dw_FileDeleted; // remove event handler
dw.DirectoryUnavailable +=
dw_DirectoryUnavailable;
dw.DirectoryUnavailableTimerStatus = true;
replacedert.IsTrue(dw.DirectoryUnavailableTimerStatus, "Timer should be enabled");
dw.EnableRaisingEvents = false; //stop other events firing
mydir.Delete();
_TestTrigger.WaitOne(8000);
replacedert.IsTrue(bHandlerRaised, "Del Dir Event not raised");
replacedert.IsFalse(System.IO.Directory.Exists(mydir.Path), "Directory should not exist");
dw.DirectoryUnavailable -= dw_DirectoryUnavailable;
dw = null;
}
catch (Exception e)
{
replacedert.Fail("Delete File in dir test failed e={0}", e);
}
finally
{
dw = null;
_TestTrigger = null;
}
}
19
Source : PluginServer.cs
with MIT License
from Autodesk-Forge
with MIT License
from Autodesk-Forge
public void Deactivate()
{
Trace.TraceInformation(": UpdateIPTParam: deactivating... ");
// Release objects.
Marshal.ReleaseComObject(_inventorServer);
_inventorServer = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
19
Source : WeakReferenceTests.cs
with MIT License
from AvaloniaUI
with MIT License
from AvaloniaUI
static void GarbageCollect()
{
for (int i = 0; i < 3; i++)
{
GC.WaitForPendingFinalizers();
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
}
}
19
Source : CommonUtils.cs
with Apache License 2.0
from aws
with Apache License 2.0
from aws
public static void RunGarbageCollection(ILogger logger, string callerInfo)
{
try
{
logger?.LogDebug("CallerInfo: " + callerInfo);
logger?.LogDebug("Memory used before collection: {0:N0}",
GC.GetTotalMemory(false));
GC.Collect();
GC.WaitForPendingFinalizers();
}
catch (System.Exception)
{
//sometimes GC.Collet/WaitForPendingFinalizers crashes
}
finally
{
logger?.LogDebug("Memory used after full collection: {0:N0}",
GC.GetTotalMemory(false));
}
}
19
Source : AyCommon.cs
with MIT License
from ay2015
with MIT License
from ay2015
[Pure]
public static void MemoryGC()
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
19
Source : Gc.cs
with MIT License
from azist
with MIT License
from azist
public override string Execute()
{
var watch = Stopwatch.StartNew();
var before = GC.GetTotalMemory(false);
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true);
if (m_Args.Of("wait").ValueAsBool())
{
GC.WaitForPendingFinalizers();
}
var after = GC.GetTotalMemory(false);
var freed = before - after;
return "GC took {0:n0} ms. and freed {1:n0}".Args(watch.ElapsedMilliseconds, IOUtils.FormatByteSizeWithPrefix(freed, longPfx: true));
}
19
Source : Timeline.axaml.cs
with MIT License
from b-editor
with MIT License
from b-editor
private async void ClipsCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
await Dispatcher.UIThread.InvokeAsync(() =>
{
if (e.Action == NotifyCollectionChangedAction.Add)
{
var item = Scene.Datas[e.NewStartingIndex];
_timelinePanel.Children.Add(item.GetCreateClipViewSafe());
}
else if (e.Action == NotifyCollectionChangedAction.Remove)
{
var item = e.OldItems![0];
if (item is ClipElement clip)
{
var view = clip.GetCreateClipViewSafe();
(view.Parent as Grid)?.Children?.Remove(view);
clip.ClearDisposable();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
}
});
}
19
Source : CoopManaged_TestConstructorWrapping.cs
with MIT License
from Bannerlord-Coop-Team
with MIT License
from Bannerlord-Coop-Team
[Fact]
private void BarIsReleased()
{
// Bar is not patched at all, this this just verifies that the method of tracking the finalizer call actually works.
WeakReference<Bar> reference = null;
var finalizerCalled = false;
new Action(() =>
{
var bar = new Bar();
bar.OnFinalizerCalled = () => { finalizerCalled = true; };
reference = new WeakReference<Bar>(bar, false);
bar = null;
})();
// Release the instance
GC.Collect();
GC.WaitForPendingFinalizers();
replacedert.False(reference.TryGetTarget(out var restoredInstance));
replacedert.Null(restoredInstance);
replacedert.True(finalizerCalled);
}
19
Source : CoopManaged_TestConstructorWrapping.cs
with MIT License
from Bannerlord-Coop-Team
with MIT License
from Bannerlord-Coop-Team
[Fact]
private void FooIsReleased()
{
WeakReference<Foo> reference = null;
var finalizerCalled = false;
new Action(() =>
{
var foo = new Foo();
foo.OnFinalizerCalled = () => { finalizerCalled = true; };
reference = new WeakReference<Foo>(foo, false);
foo = null;
})();
// Release the instance
GC.Collect();
GC.WaitForPendingFinalizers();
replacedert.False(reference.TryGetTarget(out var restoredFoo));
replacedert.Null(restoredFoo);
replacedert.True(finalizerCalled);
}
19
Source : CoopManaged_TestConstructorWrapping.cs
with MIT License
from Bannerlord-Coop-Team
with MIT License
from Bannerlord-Coop-Team
[Fact]
private void BazIsReleased()
{
WeakReference<Baz> reference = null;
var managedFinalizerCalled = false;
new Action(() =>
{
var baz = new Baz();
// Set finalizer callback on the managed instance
var managedBaz = CoopManagedBaz.CreatedInstances[baz];
CoopManagedBaz.CreatedInstances.Remove(baz);
managedBaz.OnFinalizerCalled = () => { managedFinalizerCalled = true; };
reference = new WeakReference<Baz>(baz, false);
baz = null;
})();
// Release the instance
GC.Collect();
GC.WaitForPendingFinalizers();
replacedert.False(reference.TryGetTarget(out var restoredBaz));
replacedert.Null(restoredBaz);
// Check if the managed instance was released as well. Since Baz does not have a destructor, we have to
// wait for the internal garbage collection of CoopManaged.
Thread.Sleep(CoopManagedBaz.GCInterval_ms + 50);
GC.Collect();
GC.WaitForPendingFinalizers();
replacedert.True(managedFinalizerCalled);
}
19
Source : WorldServer.cs
with MIT License
from barncastle
with MIT License
from barncastle
private static void Main()
{
CultureInfo.CurrentCulture = CultureInfo.CurrentUICulture = CultureInfo.DefaultThreadCurrentCulture = CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture;
Log.Message(LogType.INIT, " AIO SANDBOX ");
Log.Message(LogType.INIT, " REALM/PROXY/WORLD ");
Log.Message();
Log.Message(LogType.NORMAL, "Starting AIO Sandbox WorldServer...");
Log.Message();
// Load Plugins
PluginHandler pluginHandler = new PluginHandler();
Sandbox = pluginHandler.SandboxSelector();
RealmManager.RealmSession = new RealmSocket();
WorldManager.WorldSession = new WorldSocket();
if (WorldManager.WorldSession.Start() && RealmManager.RealmSession.Start())
{
Authenticator.LoadConfig();
RealmManager.RealmSession.StartRealmThread();
RealmManager.RealmSession.StartProxyThread();
WorldManager.WorldSession.StartConnectionThread();
Log.Message();
Log.Message(LogType.NORMAL, "Loading {0}", Sandbox.RealmName);
Log.Message(LogType.NORMAL, "RealmProxy listening on {0} port(s) {1}.", "127.0.0.1", Sandbox.RealmPort);
Log.Message(LogType.NORMAL, "RedirectServer listening on {0} port {1}.", "127.0.0.1", Sandbox.RedirectPort);
Log.Message(LogType.NORMAL, "WorldServer listening on {0} port {1}.", "127.0.0.1", Sandbox.WorldPort);
Log.Message(LogType.NORMAL, "Started {0}", Sandbox.RealmName);
Log.Message();
Log.Message(LogType.NORMAL, "Default client preplacedword set to \"{0}\"", Authenticator.Preplacedword);
Log.Message();
HandlerDefinitions.InitializePacketHandler();
AreaTriggers.Initialize(Sandbox);
Worldports.Initialize(Sandbox);
}
else
{
if (!WorldManager.WorldSession.Started)
Log.Message(LogType.ERROR, "WorldServer couldn't be started.");
if (!RealmManager.RealmSession.Started)
Log.Message(LogType.ERROR, "RealmServer couldn't be started.");
Log.Message();
}
GC.Collect();
GC.WaitForPendingFinalizers();
}
19
Source : GarbageCollectionUtils.cs
with GNU Lesser General Public License v3.0
from Barsonax
with GNU Lesser General Public License v3.0
from Barsonax
[MethodImpl(MethodImplOptions.NoInlining)]
public static void CheckIfCleanedUp(Func<CleanupTestSet> func)
{
CleanupTestSet cleanupTestSet = func();
// In some cases unloading something happens async and can take some time such as with replacedemblyLoadContext. Workaround this by retrying a couple of times..
for (int i = 0; cleanupTestSet.WeakReferences.Any(x => x.IsAlive) && i < 10; i++)
{
GC.Collect(2, GCCollectionMode.Forced, true);
GC.WaitForPendingFinalizers();
}
replacedert.Collection(cleanupTestSet.WeakReferences, x => replacedert.False(x.IsAlive));
}
19
Source : ImageEditor.cs
with MIT License
from BitooBit
with MIT License
from BitooBit
internal void SetImage(SKBitmap bitmap = null)
{
if (!imageSetLock)
{
imageSetLock = true;
if (bitmap != null)
{
taskCompletionEditImage.SetResult(SkiaHelper.SKBitmapToBytes(bitmap));
}
else
taskCompletionEditImage.SetResult(null);
if (page != null)
{
page.Dispose();
page = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
}
19
Source : LuaEnv.cs
with MIT License
from blueberryzzz
with MIT License
from blueberryzzz
public void Dispose()
{
FullGc();
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
Dispose(true);
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
}
19
Source : UseCase.cs
with MIT License
from bottlenoselabs
with MIT License
from bottlenoselabs
private static void GarbageCollect()
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
19
Source : ProfilerController.cs
with MIT License
from brunomikoski
with MIT License
from brunomikoski
public static void ProfileAction( int numberOfTimes, Action targetAction )
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
targetAction();
Stopwatch stopwatch = new Stopwatch();
List<long> allTicks = new List<long>();
for ( int i = 0; i < numberOfTimes; i++ )
{
stopwatch.Reset();
stopwatch.Start();
targetAction();
stopwatch.Stop();
allTicks.Add( stopwatch.ElapsedTicks );
}
long average = GetAverage( allTicks );
UnityEngine.Debug.Log( "Average Ticks: " + average );
}
19
Source : Test.cs
with Apache License 2.0
from bubibubi
with Apache License 2.0
from bubibubi
public void Run()
{
bool oldJetShowSqlStatements = JetConfiguration.ShowSqlStatements;
JetConfiguration.ShowSqlStatements = false;
DbConnection connection = GetConnection();
for (int i = 0; i < 100; i++)
{
base.CreateContext();
for (int j = 0; j < 50; j++)
{
Student student = new Student()
{
StudentName = string.Format("Student name {0}", i * 100 + j),
Notes = string.Format("Student notes {0}", i * 100 + j),
Standard = new Standard() { StandardName = string.Format("Standard of student {0}", i * 100 + j) }
};
Context.Students.Add(student);
}
Context.SaveChanges();
}
Console.WriteLine("Connection state {0}", connection.State);
connection.Open();
GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect();
PrintUsedMemory();
long usedMemory = GetUsedMemory();
for (int j = 0; j < 5; j++)
{
for (int i = 0; i < 15; i++)
{
// ReSharper disable once ReturnValueOfPureMethodIsNotUsed
Context.Students.ToList();
//Context.Dispose();
}
GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect();
PrintUsedMemory();
}
connection.Dispose();
GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect();
replacedert.IsFalse(GetUsedMemory()-usedMemory > 10000000, "Memory leakage");
JetConfiguration.ShowSqlStatements = oldJetShowSqlStatements;
}
19
Source : DatabaseFixture.cs
with Microsoft Public License
from bubibubi
with Microsoft Public License
from bubibubi
public void Dispose()
{
Connection.Close();
Connection.Dispose();
//https://stackoverflow.com/a/8513453/1872200
GC.Collect();
GC.WaitForPendingFinalizers();
File.Delete(databaseFilePath);
}
19
Source : ExternRefTests.cs
with Apache License 2.0
from bytecodealliance
with Apache License 2.0
from bytecodealliance
[Fact]
unsafe public void ItCollectsExternRefs()
{
var counter = 0;
RunTest(&counter);
GC.Collect();
GC.WaitForPendingFinalizers();
counter.Should().Be(0);
void RunTest(int* counter)
{
var instance = Linker.Instantiate(Store, Fixture.Module);
var inout = instance.GetFunction(Store, "inout");
inout.Should().NotBeNull();
for (int i = 0; i < 100; ++i)
{
inout.Invoke(Store, new Value(counter));
}
Store.Dispose();
Store = null;
}
}
19
Source : FunctionTests.cs
with Apache License 2.0
from bytecodealliance
with Apache License 2.0
from bytecodealliance
[Fact]
public void ItBindsImportMethodsAndCallsThemCorrectly()
{
var instance = Linker.Instantiate(Store, Fixture.Module);
var add = instance.GetFunction(Store, "add");
var swap = instance.GetFunction(Store, "swap");
var check = instance.GetFunction(Store, "check_string");
int x = (int)add.Invoke(Store, 40, 2);
x.Should().Be(42);
x = (int)add.Invoke(Store, 22, 5);
x.Should().Be(27);
object[] results = (object[])swap.Invoke(Store, 10, 100);
results.Should().Equal(new object[] { 100, 10 });
check.Invoke(Store);
// Collect garbage to make sure delegate function pointers preplaceded to wasmtime are rooted.
GC.Collect();
GC.WaitForPendingFinalizers();
x = (int)add.Invoke(Store, 1970, 50);
x.Should().Be(2020);
results = (object[])swap.Invoke(Store, 2020, 1970);
results.Should().Equal(new object[] { 1970, 2020 });
check.Invoke(Store);
}
19
Source : StandardAddInServer.cs
with MIT License
from CADstudioCZ
with MIT License
from CADstudioCZ
public void Deactivate()
{
//Remove event handlers
userInputEvents.OnSelect -= UserInputEvents_OnSelect;
userInputEvents.OnUnSelect -= UserInputEvents_OnUnSelect;
applicationEvents.OnActivateDoreplacedent -= ApplicationEvents_OnActivateDoreplacedent;
applicationEvents.OnDeactivateDoreplacedent -= ApplicationEvents_OnDeactivateDoreplacedent;
applicationEvents.OnDoreplacedentChange -= ApplicationEvents_OnDoreplacedentChange;
//Cleanup selectionPropertyGrid
SelectedObject = null;
selectionPropertyGrid = null;
// Release objects.
applicationEvents = null;
userInputEvents = null;
inventor = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
19
Source : Program.cs
with GNU General Public License v3.0
from caioavidal
with GNU General Public License v3.0
from caioavidal
public static void Main()
{
Console.replacedle = "OpenCoreMMO Server";
var sw = new Stopwatch();
sw.Start();
var cancellationTokenSource = new CancellationTokenSource();
var cancellationToken = cancellationTokenSource.Token;
var container = Container.BuildConfigurations();
var (serverConfiguration, _, logConfiguration) = (container.Resolve<ServerConfiguration>(),
container.Resolve<GameConfiguration>(), container.Resolve<LogConfiguration>());
var (logger, _) = (container.Resolve<ILogger>(), container.Resolve<LoggerConfiguration>());
logger.Information("Welcome to OpenCoreMMO Server!");
logger.Information("Log set to: {log}", logConfiguration.MinimumLevel);
logger.Information("Environment: {env}", Environment.GetEnvironmentVariable("ENVIRONMENT"));
logger.Step("Building extensions...", "{files} extensions builded",
() => ExtensionsCompiler.Compile(serverConfiguration.Data, serverConfiguration.Extensions));
container = Container.BuildAll();
var databaseConfiguration = container.Resolve<DatabaseConfiguration>();
var context = container.Resolve<NeoContext>();
logger.Step("Loading database: {db}", "{db} database loaded",
action: () => context.Database.EnsureCreatedAsync(cancellationToken),
databaseConfiguration.Active);
RSA.LoadPem(serverConfiguration.Data);
container.Resolve<IEnumerable<IRunBeforeLoaders>>().ToList().ForEach(x => x.Run());
container.Resolve<ItemTypeLoader>().Load();
container.Resolve<WorldLoader>().Load();
container.Resolve<SpawnLoader>().Load();
container.Resolve<MonsterLoader>().Load();
container.Resolve<VocationLoader>().Load();
container.Resolve<SpellLoader>().Load();
container.Resolve<IEnumerable<IStartupLoader>>().ToList().ForEach(x => x.Load());
container.Resolve<SpawnManager>().StartSpawn();
var scheduler = container.Resolve<IScheduler>();
var dispatcher = container.Resolve<IDispatcher>();
dispatcher.Start(cancellationToken);
scheduler.Start(cancellationToken);
scheduler.AddEvent(new SchedulerEvent(1000, container.Resolve<GameCreatureJob>().StartChecking));
scheduler.AddEvent(new SchedulerEvent(1000, container.Resolve<GameItemJob>().StartChecking));
scheduler.AddEvent(new SchedulerEvent(1000, container.Resolve<GameChatChannelJob>().StartChecking));
container.Resolve<PlayerPersistenceJob>().Start(cancellationToken);
container.Resolve<EventSubscriber>().AttachEvents();
container.Resolve<LuaGlobalRegister>().Register();
var listeningTask = StartListening(container, cancellationToken);
container.Resolve<IEnumerable<IStartup>>().ToList().ForEach(x => x.Run());
container.Resolve<IGameServer>().Open();
sw.Stop();
logger.Step("Running Garbage Collector", "Garbage collected", () =>
{
GC.Collect();
GC.WaitForPendingFinalizers();
});
logger.Information("Memory usage: {mem} MB",
Math.Round(Process.GetCurrentProcess().WorkingSet64 / 1024f / 1024f, 2));
logger.Information("Server is {up}! {time} ms", "up", sw.ElapsedMilliseconds);
listeningTask.Wait(cancellationToken);
}
19
Source : Program.cs
with MIT License
from CefNet
with MIT License
from CefNet
[STAThread]
public unsafe static void Main(string[] args)
{
string cefPath = Path.Combine(Path.GetDirectoryName(GetProjectPath()), "cef");
var path = Environment.GetEnvironmentVariable("PATH");
Environment.SetEnvironmentVariable("PATH", Path.Combine(cefPath, "Release") + ";" + path);
string libname = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "libcef.dll" : "libcef.so";
IntPtr pLibCef = NativeMethods.LoadLibrary(Path.Combine(cefPath, "Release", libname));
// This executable is called many times, because it
// is also used for subprocesses. Let's print args
// so we can differentiate between main process and
// subprocesses. If one of the first args is for
// example "--type=renderer" then it means that
// this is a Renderer process. There may be more
// subprocesses like GPU (--type=gpu-process) and
// others. On Linux there are also special Zygote
// processes.
Console.Write("\nProcess args: ");
if (args.Length == 0)
{
Console.Write("none (Main process)");
}
else
{
Console.WriteLine();
for (int i = 0; i < args.Length; i++)
{
if (args[i].Length > 128)
Console.WriteLine(args[i].Remove(128) + "...");
else
Console.WriteLine(args[i]);
}
}
Console.Write("\n\n");
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)
&& !args.Any(arg => arg.StartsWith("--type="))
&& !args.Contains("--no-zygote"))
{
Console.WriteLine("Please run with --no-zygote");
return;
}
// CEF version
if (args.Length == 0)
{
var version = new int[8];
for (int i = 0; i < version.Length; i++)
{
version[i] = CefApi.CefVersionInfo((CefVersionComponent)i);
}
Console.Write("CEF version: {0}\n", string.Join(".", version));
}
// Main args
CefMainArgs main_args = CefMainArgs.CreateDefault();
// Cef app
var app = new CefApp();
// Execute subprocesses. It is also possible to have
// a separate executable for subprocesses by setting
// cef_settings_t.browser_subprocess_path. In such
// case cef_execute_process should not be called here.
Console.Write("cef_execute_process, argc={0}\n", args.Length);
int code = CefApi.ExecuteProcess(main_args, app, IntPtr.Zero);
if (code >= 0)
{
main_args.Dispose();
Environment.Exit(code);
}
// Application settings. It is mandatory to set the
// "size" member.
var settings = new CefSettings();
//settings.MulreplacedhreadedMessageLoop = true;
settings.LocalesDirPath = Path.Combine(cefPath, "Resources", "locales");
settings.ResourcesDirPath = Path.Combine(cefPath, "Resources");
settings.LogSeverity = CefLogSeverity.Warning; // Show only warnings/errors
settings.NoSandbox = true;
settings.WindowlessRenderingEnabled = true;
// Initialize CEF
Console.Write("cef_initialize\n");
CefApi.Initialize(main_args, settings, app, IntPtr.Zero);
GC.KeepAlive(settings);
main_args.Dispose();
// Window info
var windowInfo = new CefWindowInfo();
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
windowInfo.SetAsPopup(IntPtr.Zero, "cefapi example");
else
windowInfo.WindowName = "cefapi example";
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
NativeMethods.XSetErrorHandler(x11_error_handler);
NativeMethods.XSetIOErrorHandler(x11_io_error_handler);
}
var browserSettings = new CefBrowserSettings();
// Client handlers
var client = new CefClientClreplaced();
// Create browser asynchronously. There is also a
// synchronous version of this function available.
Console.WriteLine("cef_browser_host_create_browser");
bool cbok = CefApi.CreateBrowser(windowInfo, client, "https://yandex.com/", browserSettings, null, null);
Console.WriteLine("CreateBrowser: {0}", cbok);
windowInfo.Dispose();
// Message loop. There is also cef_do_message_loop_work()
// that allow for integrating with existing message loops.
// On Windows for best performance you should set
// cef_settings_t.multi_threaded_message_loop to true.
// Note however that when you do that CEF UI thread is no
// more application main thread and using CEF API is more
// difficult and require using functions like cef_post_task
// for running tasks on CEF UI thread.
Console.WriteLine("cef_run_message_loop\n");
CefApi.RunMessageLoop();
// Release references to CefBrowser's (if any)
GC.Collect();
GC.WaitForPendingFinalizers();
// Shutdown CEF
Console.WriteLine("cef_shutdown\n");
CefApi.Shutdown();
GC.KeepAlive(client);
}
19
Source : CefNetApplication.cs
with MIT License
from CefNet
with MIT License
from CefNet
public async void SignalForShutdown(Action callback)
{
var shutdownTaskSource = new TaskCompletionSource<bool>();
shutdownTaskSource = Interlocked.CompareExchange(ref _shutdownSignalTaskSource, shutdownTaskSource, null) ?? shutdownTaskSource;
if (Volatile.Read(ref _browsersCount) == 0)
shutdownTaskSource.TrySetResult(false);
await shutdownTaskSource.Task.ConfigureAwait(false);
GC.Collect();
GC.WaitForPendingFinalizers();
callback();
}
19
Source : CefNetApplication.cs
with MIT License
from CefNet
with MIT License
from CefNet
public void Shutdown()
{
replacedertAccess();
GC.Collect();
GC.WaitForPendingFinalizers();
CefApi.Shutdown();
}
See More Examples