Exemplo n.º 1
0
    private void ShootGun(Transform activeRig, Item equipedWeapon)
    {
        GarbageCollector.CollectIncremental((ulong)0.1f);

        gunReloadController = equipedWeapon.GetComponent <GunReloadController>();

        if (InventoryManager.Instance.MenuOpen || gunReloadController.isReloading)
        {
            return;
        }

        SetGunData(activeRig, equipedWeapon);

        //recoilUpKick = Random.Range(1, (float)recoilUpKick);
        recoilSideKick = Random.Range(-recoilSideKick, recoilSideKick);

        bulletDropOff = bulletDrop; //sets data for projectiles dropoff method

        if (Input.GetKey(KeyCode.Mouse0) && Time.time >= timeToFire && isAutomatic && gunReloadController.currentHoldingAmmo > 0)
        {
            timeToFire = Time.time + 1f / fireRate;

            bulletInstance = ShootBullet(equipedWeapon, bullet.name, shell, shellEjectPoint, shootPoint, facingDir, forceMultiplier, shootSounds, recoilUpKick, recoilSideKick);
            bulletInstance.GetComponent <Projectile>().InitializeBullet(bulletDamage);
            return;
        }
        else if (Input.GetKeyDown(KeyCode.Mouse0) && Time.time >= timeToFire && gunReloadController.currentHoldingAmmo > 0)
        {
            timeToFire = Time.time + 1f / fireRate;

            bulletInstance = ShootBullet(equipedWeapon, bullet.name, shell, shellEjectPoint, shootPoint, facingDir, forceMultiplier, shootSounds, recoilUpKick, recoilSideKick);
            bulletInstance.GetComponent <Projectile>().InitializeBullet(bulletDamage);
        }
    }
Exemplo n.º 2
0
        virtual public string Init(ulong nClientBrowserID, string sVersionOfSCR)
        {
            (new Logger()).WriteWarning("________________INIT   begin");
            if (_sVersionOfXapScr == null)
            {
                _sVersionOfXapScr = helpers.replica.scr.XAP.GetVersionOfDll(@"ClientBin\scr.xap", @"ClientBin\scr.dll");
            }
            if (sVersionOfSCR != _sVersionOfXapScr)
            {
                (new Logger()).WriteError("init. client's version doesn't match [client=" + sVersionOfSCR + "][server=" + _sVersionOfXapScr + "]");
                return("не совпадают версии SCR [client=" + sVersionOfSCR + "][server=" + _sVersionOfXapScr + "]");
            }

            string sRetVal = "";

            (new Logger()).WriteDebug2("init [browser:" + nClientBrowserID + "][client:" + Client.nID + "][last:" + Client.dtPing + "][client_ver=" + sVersionOfSCR + "]");
#if DEBUG
            if (true)
#else
            if (DateTime.Now > Client.dtPing.AddSeconds(20) || IsClientCurrent(nClientBrowserID))
#endif
            {
                ClientInit(nClientBrowserID);
            }
            //else if (null == Session["ClientID"])
            //    Session["ClientID"] = Client.nID;
            //else if (!IsClientCurrent(nClientBrowserID))
            else
            {
                return((Session["ClientID"] ?? "null") + ":" + Client.nCurrentClientBrowserID + ":" + nClientBrowserID + ":" + " клиент управления автоматизацией аппаратно-студийного блока уже запущен в другом окне браузера или на другой рабочей станции");
            }

            if (!GarbageCollector.IsRunning())
            {
                try
                {
                    (new Logger()).WriteDebug2("init:text");
                    Template cText = new Template("");                     // взмолаживание девайса
                    cText.TextCreate(".");
                    cText.Prepare();
                    cText.Start();
                    System.Threading.Thread.Sleep(1000);
                    cText.Stop();

                    (new Logger()).WriteDebug2("init:discom");
                    //(new userspace.Helper()).DisComInit(); // взмолаживание сридов для просчета чата.  // чат считается в устройстве из префов, так что это не всегда DisCom
                }
                catch (Exception ex)
                {
                    sRetVal = "не пройдена инициализация сервиса";
                    (new Logger()).WriteError(ex);
                }
                if ("" == sRetVal)
                {
                    GarbageCollector.Run();
                }
            }
            (new Logger()).WriteWarning("________________INIT   end   " + sRetVal);
            return(sRetVal);
        }
Exemplo n.º 3
0
        public void DoubleReferenceCreateOneRemoveAndObjectStillNotGarbageCollected()
        {
            var gc = new GarbageCollector();

            var rootEntry = new StorageEntry(0, "Next", 1);
            var node_1a   = new StorageEntry(1, "Next_A", 2);
            var node_1b   = new StorageEntry(1, "Next_B", 3);
            var node_2    = new StorageEntry(2, "Next", 3);

            var collectables = gc.Collect(
                new List <StorageEntry> {
                rootEntry, node_1a, node_1b, node_2
            },
                Enumerable.Empty <ObjectIdAndKey>()
                ).ToArray();

            collectables.Length.ShouldBe(0);

            collectables = gc.Collect(
                new List <StorageEntry>()
            {
                new StorageEntry(2, "Next", null)
            },
                Enumerable.Empty <ObjectIdAndKey>()
                ).ToArray();

            collectables.Length.ShouldBe(0);
        }
Exemplo n.º 4
0
        public bool ItemStop(Item cItem)
        {
            bool bRetVal    = false;
            Item cItemLocal = null;

            try
            {
                if (0 < Client.nID)
                {
                    if (null != (cItemLocal = GarbageCollector.ItemGet(cItem)))
                    {
                        (new Logger()).WriteDebug2("stop: " + cItemLocal.ToString());
                        cItemLocal.Stop();
                        bRetVal = true;
                    }
                    else
                    {
                        (new Logger()).WriteError("item:stop: указанный элемент не зарегистрирован [item:" + cItem.GetHashCode() + "]");
                    }
                }
                else
                {
                    (new Logger()).WriteError("item:stop: не инициирован механизм регистрации клиента");
                }
            }
            catch (Exception ex)
            {
                if (null != cItemLocal)
                {
                    cItemLocal.eStatus = Item.Status.Error;
                }
                (new Logger()).WriteError(ex);
            }
            return(bRetVal);
        }
        public EagerTensor Resolve()
        {
            _id = c_api.TFE_EagerTensorId(EagerTensorHandle);

            if (tfe_tensor_handle == IntPtr.Zero)
            {
                tfe_tensor_handle = c_api.TFE_EagerTensorHandle(EagerTensorHandle);
            }

            if (_handle == IntPtr.Zero)
            {
                _handle = c_api.TFE_TensorHandleResolve(tfe_tensor_handle, status);
            }

            /*print($"new Tensor {Id} {_handle.ToString("x16")}");
             * print($"new TensorHandle {Id} {tfe_tensor_handle.ToString("x16")}");
             * print($"new EagerTensor {Id} {EagerTensorHandle.ToString("x16")}");*/

            if (tfe_tensor_handle == IntPtr.Zero && _id == 0)
            {
            }

            GarbageCollector.Increase(_handle, GCItemType.TensorHandle);
            GarbageCollector.Increase(tfe_tensor_handle, GCItemType.LocalTensorHandle);
            GarbageCollector.Increase(EagerTensorHandle, GCItemType.EagerTensorHandle);

            return(this);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Generates export file
        /// </summary>
        /// <param name="dt">Data table</param>
        /// <param name="path">Path</param>
        public void GenerateFile(DataTable dt, string path)
        {
            IWorkbook workbook = new HSSFWorkbook();

            ISheet worksheet = workbook.CreateSheet("data");

            GenerateStructure(worksheet, dt.Rows.Count + 1, dt.Columns.Count);
            ICellStyle headerCellStyle = CreateHeaderCellStyle(workbook);
            ICellStyle dataCellStyle   = CreateDataCellStyle(workbook);

            for (int i = 0; i < dt.Columns.Count; i++)
            {
                DataColumn dataColumn = dt.Columns[i];
                worksheet.SetColumnWidth(i, 10000);

                ICell headerCell = GetCell(worksheet, 0, i);
                headerCell.SetCellValue(dataColumn.ColumnName);
                headerCell.CellStyle = headerCellStyle;

                for (int j = 0; j < dt.Rows.Count; j++)
                {
                    ICell cell = GetCell(worksheet, j + 1, i);
                    cell.SetCellValue(dt.Rows[j][i].ToStr());
                    cell.CellStyle = dataCellStyle;
                }
            }

            using (FileStream stream = new FileStream(path, FileMode.Create, FileAccess.ReadWrite))
            {
                workbook.Write(stream);
            }

            GarbageCollector.Collect();
        }
Exemplo n.º 7
0
        public bool ItemDelete(Item cItem)
        {
            bool bRetVal = false;

            try
            {
                if (0 < Client.nID)
                {
                    Item cItemLocal = GarbageCollector.ItemGet(cItem);
                    if (null != cItemLocal)
                    {
                        (new Logger()).WriteDebug2("delete: " + cItemLocal.ToString());
                        GarbageCollector.ItemDelete(cItemLocal);
                        bRetVal = true;
                    }
                    else
                    {
                        (new Logger()).WriteError("item:delete: указанный элемент не зарегистрирован [item:" + cItem.GetHashCode() + "]");
                    }
                }
                else
                {
                    (new Logger()).WriteError("item:delete: не инициирован механизм регистрации клиента");
                }
            }
            catch (Exception ex)
            {
                (new Logger()).WriteError(ex);
            }
            return(bRetVal);
        }
Exemplo n.º 8
0
        public Item ItemCreate(string sPreset, string sFile, UserReplacement[] aUserReplacements)          // aUserReplacements  может быть null, nAssetsID  может быть 0
        {
            Item cRetVal = null;

            try
            {
                if (0 < Client.nID)
                {
                    string sInfo = "Template, " + sFile;
                    if (null != (cRetVal = GarbageCollector.ItemGet(sInfo)) && cRetVal.eStatus != Item.Status.Stopped && cRetVal.eStatus != Item.Status.Error)
                    {
                        return(cRetVal);
                    }
                    cRetVal         = new Template(sFile, (null == aUserReplacements ? null : aUserReplacements.ToDictionary(row => row.sKey, row => row.sValue)));
                    cRetVal.sPreset = sPreset;
                    cRetVal.sInfo   = sInfo;
                    GarbageCollector.ItemAdd(cRetVal);
                    (new Logger()).WriteDebug3("create: " + sInfo + " hash:[" + cRetVal.GetHashCode() + "]");
                }
                else
                {
                    (new Logger()).WriteError("create: не инициирован механизм регистрации клиента");
                }
            }
            catch (Exception ex)
            {
                (new Logger()).WriteError(ex);
            }
            return(cRetVal);
        }
Exemplo n.º 9
0
        private void Test(bool[] rowsToKeep)
        {
            int count = rowsToKeep.Length;

            // Build an identity column
            NumberColumn <int> column = new NumberColumn <int>(-1);

            for (int i = 0; i < rowsToKeep.Length; ++i)
            {
                column[i] = i;
            }

            // Build a RowUpdater and fake mapping to temp to check those results
            TableStub  table   = new TableStub();
            RowUpdater updater = new RowUpdater(table, table);

            int[] rowsToTemp = Enumerable.Range(10, count).ToArray();

            // Request Garbage Collection
            GarbageCollector.Collect <int>(column, null, rowsToKeep, updater, rowsToTemp);

            // Verify correct values were kept
            StringBuilder expected      = new StringBuilder();
            int           expectedCount = 0;

            for (int i = 0; i < count; ++i)
            {
                if (rowsToKeep[i])
                {
                    expectedCount++;

                    if (expected.Length > 0)
                    {
                        expected.Append(", ");
                    }
                    expected.Append(i);
                }
            }

            Assert.Equal(expectedCount, column.Count);
            Assert.Equal(expected.ToString(), String.Join(", ", column.OrderBy((i) => i)));

            // Verify rows removed are reported in the correct indices in temp or swapped in original column
            RowStub stub = new RowStub(table, 0);

            for (int i = 0; i < count; ++i)
            {
                stub.Index = i;
                updater.Update(stub);

                if (!rowsToKeep[i])
                {
                    Assert.Equal(10 + i, stub.Index);
                }
                else
                {
                    Assert.Equal(i, column[stub.Index]);
                }
            }
        }
Exemplo n.º 10
0
        void CollectGarbageOnDemand()
        {
            if (!UIWidgetsGlobalConfiguration.EnableIncrementalGC)
            {
                return;
            }

            var mem = Profiler.GetMonoUsedSizeLong();

            if (mem < lastFrameMemory)
            {
                // GC happened.
                nextCollectAt = mem + kCollectAfterAllocating;
            }
            else if (mem >= nextCollectAt)
            {
                // Trigger incremental GC
                GarbageCollector.GCMode = GarbageCollector.Mode.Enabled;
                GarbageCollector.CollectIncremental(1000);
                lastFrameMemory         = mem + kCollectAfterAllocating;
                GarbageCollector.GCMode = GarbageCollector.Mode.Disabled;
            }

            lastFrameMemory = mem;
        }
Exemplo n.º 11
0
 public GameplayScreen()
 {
     Camera2D         = new Camera2D();
     GarbageCollector = new GarbageCollector(20);
     Textures.GameplayBackgroundAnimation = new Animation2D();
     GameplayBackground = new GameplayBackground(Textures.GameplayBackgroundTexture,
                                                 Textures.GameplayBackgroundAnimation);
 }
Exemplo n.º 12
0
    void Start()
    {
        garboCollector = FindObjectOfType <GarbageCollector>();
        PathFinder        pathfinder = FindObjectOfType <PathFinder>();
        List <Waypointer> path       = pathfinder.PathfindingController();

        StartCoroutine(WaypointReader(path));
    }
Exemplo n.º 13
0
        /// <summary>
        /// Applies filters
        /// </summary>
        /// <param name="filters">Filters</param>
        public void ApplyFilters(List <Filter> filters)
        {
            try
            {
                // Saving original image
                if (AppliedFilters.Count == 0)
                {
                    OriginalFileName = GenerateOriginalFileName(ImageFileName);
                    File.Copy(ImageFilePath, OriginalFilePath, true);
                }

                // Creating temp image
                if (TempFilePath.IsNullOrEmpty())
                {
                    TempFilePath = Path.Combine(ImageFolderPath, GenerateTempFileName(ImageFileName));
                    File.Copy(ImageFilePath, TempFilePath, true);
                }

                foreach (Filter filter in filters)
                {
                    try
                    {
                        // Applying filter
                        Bitmap original = new Bitmap(TempFilePath);
                        Bitmap bitmap   = new Bitmap(original);
                        original.Dispose();
                        File.Delete(TempFilePath);
                        ApplyFilter(bitmap, filter).Save(TempFilePath, ImageFormat.Jpeg);
                        bitmap.Dispose();
                        GarbageCollector.Collect();

                        AppliedFilters.Add(filter);
                    }
                    catch (Exception e)
                    {
                        LogHelper.Logger.Error(e, $"Unable to apply filter to image. Filter name: {filter.FilterType}");
                    }
                }

                // Create thumbnail for filtered image
                if (TempThumbnailFilePath.IsNullOrEmpty())
                {
                    TempThumbnailFilePath = Path.Combine(ImageFolderPath, GenerateTempThumbnailFileName(ImageFileName));
                }
                else
                if (File.Exists(TempThumbnailFilePath))
                {
                    File.Delete(TempThumbnailFilePath);
                }
                new ImagesConverter(TempFilePath).CreateThumbnail(TempThumbnailFilePath, CommonSettings.ThumbnailWidth, CommonSettings.ThumbnailHeight);
            }
            catch (Exception e)
            {
                LogHelper.Logger.Error(e, "Unable to apply filters to image.");
            }

            GarbageCollector.Collect();
        }
Exemplo n.º 14
0
    public static void Main()
    {
        var memoryVisitor  = new MemoryVisitor();
        var memoryProfiles = new List <IMemoryProfile>()
        {
            new CacheMemory(), new SwapMemory()
        };
        var gb = new GarbageCollector(memoryProfiles, memoryVisitor);

        Console.WriteLine("Total alocated: {0}", memoryVisitor.totalAlocated);
    }
Exemplo n.º 15
0
        public void Trim()
        {
            // Trim indices first to consolidate references before garbage collection
            _indices.Trim();

            // Find any unused values and remove them
            GarbageCollector.FindUnusedAndCollect(_values, _indicesInner);

            // Trim values afterward to clean up any newly unused space
            _values.Trim();
        }
Exemplo n.º 16
0
        public bool AddTextToRoll(string sTemplateInfo, string sText)
        {
            Item     cItem = GarbageCollector.ItemGet(sTemplateInfo);
            Template cTemplate;

            if (null != cItem && cItem is Template && (cTemplate = (Template)cItem).eStatus == Item.Status.Started)
            {
                return(((Template)cItem).AddTextToRoll(sText));
            }
            return(false);
        }
Exemplo n.º 17
0
        protected override void DisposeUnmanagedResources(IntPtr handle)
        {
            GarbageCollector.Decrease(_handle);
            GarbageCollector.Decrease(tfe_tensor_handle);
            GarbageCollector.Decrease(EagerTensorHandle);

            /*print($"deleting DeleteTensorHandle {Id} {_handle.ToString("x16")}");
             * c_api.TF_DeleteTensor(_handle);
             * print($"deleting DeleteTensorHandle {Id} {tfe_tensor_handle.ToString("x16")}");
             * c_api.TFE_DeleteTensorHandle(tfe_tensor_handle);
             * print($"deleting DeleteEagerTensor {Id} {EagerTensorHandle.ToString("x16")}");
             * c_api.TFE_DeleteEagerTensor(EagerTensorHandle);*/
        }
Exemplo n.º 18
0
    public void Awake()
    {
        if (instance == null)
        {
            instance = this;
        }
        else if (instance != this)
        {
            Destroy(gameObject);
        }

        DontDestroyOnLoad(gameObject);
    }
Exemplo n.º 19
0
        /// <summary>
        /// Полное клонирование Bitmap
        /// </summary>
        /// <param name="bitmap">Bitmap</param>
        /// <param name="pixelFormat">Формат пикселей</param>
        /// <returns></returns>
        public static Bitmap CloneSmart(this Bitmap bitmap, PixelFormat pixelFormat)
        {
            Bitmap result;

            GarbageCollector.Collect();

            using (Bitmap b = new Bitmap(bitmap))
            {
                b.SetResolution(bitmap.HorizontalResolution, bitmap.VerticalResolution);
                result = b.Clone(new Rectangle(Point.Empty, new Size(b.Width, b.Height)), pixelFormat);
            }

            return(result);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Creates the thumbnail.
        /// </summary>
        /// <param name="outputPath">The output path.</param>
        /// <param name="width">Width.</param>
        /// <param name="height">Height.</param>
        public void CreateThumbnail(string outputPath, int width, int height)
        {
            GdPictureImaging image = new GdPictureImaging();
            int imageId            = image.CreateGdPictureImageFromFile(ImagePath);

            if (imageId > 0)
            {
                int thumbnailId = image.CreateThumbnailHQ(imageId, width, height, Color.Black);
                image.SaveAsJPEG(thumbnailId, outputPath);
                image.ReleaseGdPictureImage(imageId);
            }

            GarbageCollector.Collect();
        }
Exemplo n.º 21
0
        /// <summary>
        /// Creates a new virtual machine
        /// </summary>
        /// <param name="config">The configuration</param>
        /// <param name="createCompilerFn">A function to create the compiler</param>
        public VirtualMachine(VirtualMachineConfiguration config, Func <VirtualMachine, IJITCompiler> createCompilerFn)
        {
            this.Config = config;

            this.TypeProvider   = new TypeProvider(this.ClassMetadataProvider);
            this.verifier       = new Verifier(this);
            this.assemblyLoader = new AssemblyLoader(
                new ClassLoader(this.TypeProvider, this.ClassMetadataProvider),
                new FunctionLoader(this.TypeProvider),
                this.TypeProvider);

            this.CallStack        = new CallStack(this.MemoryManager, this.ManagedObjectReferences, 5000);
            this.Compiler         = createCompilerFn(this);
            this.GarbageCollector = new GarbageCollector(this);
        }
Exemplo n.º 22
0
        public MainWindow()
        {
            InitializeComponent();

            this.UseLayoutRounding = true;

            this.Loaded += (s, ea) =>
            {
                _GarbageCollector = new GarbageCollector(this);
            };

            this.Closing += (s, ea) =>
            {
                Dispose();
            };
        }
Exemplo n.º 23
0
        } // DisposeManagedResources

        #endregion

        #region Initialize

        /// <summary>
        /// Creates the scene content manager and loads the user content.
        /// </summary>
        internal void Initialize()
        {
            AssetContentManager = new AssetContentManager {
                Name = (GetType().Name + " Content Manager")
            };
            AssetContentManager.CurrentContentManager = AssetContentManager;
            GameObjectContentManager = new GameObjectContentManager {
                Name = (GetType().Name + " Content Manager")
            };
            GameObjectContentManager.CurrentContentManager = GameObjectContentManager;
            LoadContent();
            ContentLoaded = true;
            // A collection of all generations could be a good idea at this point.
            // Besides the used managed memory indicates rational values when this is executed here.
            GarbageCollector.CollectGarbage();
        } // Initialize
Exemplo n.º 24
0
        } // DisposeManagedResources

        #endregion

        #region Unload

        /// <summary>
        /// Disposes all data that was loaded by this ContentManager.
        /// </summary>
        public void Unload()
        {
            // Dispose assets
            List <GameObject> gameObjectsTemporalList = new List <GameObject>(); // An auxiliary list is needed because the original will be modified for each asset.

            gameObjectsTemporalList.AddRange(GameObjects);
            foreach (GameObject gameObject in gameObjectsTemporalList)
            {
                gameObject.ContentManager = null;
                gameObject.Dispose();
            }
            gameObjectsTemporalList.Clear();
            // A collection of all generations could be a good idea at this point.
            // Besides the used managed memory indicates rational values when this is executed here.
            GarbageCollector.CollectGarbage();
        } // Unload
Exemplo n.º 25
0
        } // GameObjectContentManager

        #endregion

        #region Dispose

        /// <summary>
        /// Dispose managed resources.
        /// </summary>
        protected override void DisposeManagedResources()
        {
            ContentManagers.Remove(this);
            areContentManagersSorted = false;
            // Dispose assets
            List <GameObject> gameObjectsTemporalList = new List <GameObject>(); // An auxiliary list is needed because the original will be modified for each asset.

            gameObjectsTemporalList.AddRange(GameObjects);
            foreach (GameObject gameObject in gameObjectsTemporalList)
            {
                gameObject.Dispose();
            }
            gameObjectsTemporalList.Clear();
            // A collection of all generations could be a good idea at this point.
            // Besides the used managed memory indicates rational values when this is executed here.
            GarbageCollector.CollectGarbage();
        } // DisposeManagedResources
Exemplo n.º 26
0
        public void Trim()
        {
            if (Count == 0)
            {
                return;
            }
            _pairs.Trim();

            // Find Key/Value pairs no longer in any Dictionaries
            BitVector rowsToKeep = new BitVector(false, _keys.Count);

            _pairsInner.ForEach((slice) => IntRemapper.Instance.AddValues(slice, rowsToKeep));

            // Remove those from Keys and Values
            GarbageCollector.Collect <int>(_keys, null, rowsToKeep);
            GarbageCollector.Collect <int>(_values, new [] { _pairsInner }, rowsToKeep);
        }
Exemplo n.º 27
0
    void Start()
    {
        //tidies up the editor, personal preference
        garboCollect = FindObjectOfType <GarbageCollector>();

        //initialize gameLogicController
        gameLogicController = FindObjectOfType <GameLogicController>();

        //initialize transforms/rotations at the beginning
        //of the game, to allow ADS functionality
        GunADSInitializer();

        //initializing our FPSController so that we can change sensitivity/etc.
        standardFPSController = GetComponentInParent <RigidbodyFirstPersonController>();

        gunAudioController = GetComponent <AudioSource>();
    }
Exemplo n.º 28
0
        public void CorrectEntriesAreCollected()
        {
            var gc = new GarbageCollector();

            var rootEntry = new StorageEntry(0, "Next", 1);
            var node_1    = new StorageEntry(1, "Next", 2);
            var node_2    = new StorageEntry(2, "Next", 3);
            var node_3    = new StorageEntry(3, "Next", 4);

            var gcs = new StorageEntry(10, "SomeKey", "SomeValue");

            var collectables = gc.Collect(
                new List <StorageEntry> {
                rootEntry, node_1, node_2, node_3, gcs
            },
                Enumerable.Empty <ObjectIdAndKey>()
                ).ToArray();

            collectables.Length.ShouldBe(1);
            collectables[0].ShouldBe(10);

            collectables = gc.Collect(
                new List <StorageEntry>()
            {
                new StorageEntry(2, "Next", null)
            },
                Enumerable.Empty <ObjectIdAndKey>()
                ).OrderBy(_ => _).ToArray();

            collectables.Length.ShouldBe(2);
            collectables[0].ShouldBe(3);
            collectables[1].ShouldBe(4);

            collectables = gc.Collect(
                new List <StorageEntry>()
            {
                new StorageEntry(0, "Next", null)
            },
                Enumerable.Empty <ObjectIdAndKey>()
                ).OrderBy(_ => _).ToArray();

            collectables.Length.ShouldBe(2);
            collectables[0].ShouldBe(1);
            collectables[1].ShouldBe(2);
        }
Exemplo n.º 29
0
        public Item[] ItemsUpdate(Item[] aItems)
        {
            if (null == Session["ClientID"])
            {
                (new Logger()).WriteError(new Exception("ItemsUpdate(): Попытка обращения с непроинициализированного клиента"));
                return(null);
            }
            Client.dtPing = DateTime.Now;
            List <Item> aRetVal = new List <Item>();

            try
            {
                //if (DateTime.Now > _dtStatusGetLast.AddMinutes(1))
                //{
                //    _dtStatusGetLast = DateTime.Now;
                //    int nTemplCount = 0;
                //    lock (_aItems)
                //        nTemplCount = _aItems.Count(o => Client.nID == o.nClientID);
                //    (new Logger()).WriteDebug2("ingenie.asmx.cs: MyPair[] EffectStatusGet: Вошли в StatusGet, aItemIDs.Length = {" + aItemIDs.Length + "}, _ahItems[nClientID].Keys.Count = {" + nTemplCount + "}");
                //}
                if (null != aItems)
                {
                    Item cItem;
                    bool bGCRunning = GarbageCollector.IsRunning();
                    for (int nIndx = 0; aItems.Length > nIndx; nIndx++)
                    {
                        if (!bGCRunning || null == (cItem = GarbageCollector.ItemGet(aItems[nIndx])))
                        {
                            (new Logger()).WriteError("items:update: указанный элемент не зарегистрирован [item:" + aItems[nIndx].GetHashCode() + "]");
                            cItem         = aItems[nIndx];
                            cItem.eStatus = Item.Status.Error;
                        }
                        aRetVal.Add(cItem);
                    }
                }
            }
            catch (Exception ex)
            {
                (new Logger()).WriteError(ex);
            }
            return(aRetVal.ToArray());
        }
Exemplo n.º 30
0
        public static void Collect()
        {
            var before = GC.GetTotalMemory(false);

            if (GarbageCollector.CollectIncremental(1000000))
            {
                if (GarbageRemains)
                {
                    var after = GC.GetTotalMemory(false);
                    Log.Warning($"collection complete - { (before - after)} Collected - {after.ToMb():0.00}MB in heap", true);
                }
                GarbageRemains = false;
                //  Log.Warning("collection complete", true);
            }
            else
            {
                GarbageRemains = true;
                //   Log.Warning("garbage remains", true);
            }
        }
Exemplo n.º 31
0
 public static void Main()
 {
     var memoryVisitor = new MemoryVisitor();
     var memoryProfiles = new List<IMemoryProfile>(){
         new CacheMemory(), new SwapMemory()
     };
     var gb = new GarbageCollector(memoryProfiles, memoryVisitor);
     Console.WriteLine("Total alocated: {0}", memoryVisitor.totalAlocated);
 }