Example #1
0
        private async void GetUsageLevel()
        {
            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                try
                {
                    AppMemoryUsageLevel usageLevel = MemoryManager.AppMemoryUsageLevel;
                    usageLevelText.Text            = usageLevel.ToString();
                    SolidColorBrush brush          = null;
                    switch (usageLevel)
                    {
                    case AppMemoryUsageLevel.High:
                        brush = new SolidColorBrush(Colors.Red);
                        break;

                    case AppMemoryUsageLevel.Medium:
                        brush = new SolidColorBrush(Colors.Orange);
                        break;

                    case AppMemoryUsageLevel.Low:
                        brush = new SolidColorBrush(Color.FromArgb(255, 0, 255, 0));
                        break;
                    }
                    usageText.Foreground      = brush;
                    usageLevelText.Foreground = brush;
                }
                catch (Exception ex)
                {
                    status.Log(ex.Message);
                }
            });
        }
Example #2
0
        private void MemoryIncreased(object sender, object e)
        {
            AppMemoryUsageLevel level = MemoryManager.AppMemoryUsageLevel;

            if (level == AppMemoryUsageLevel.OverLimit || level == AppMemoryUsageLevel.High)
            {
                GC.Collect();
            }
        }
Example #3
0
        private void MemoryManager_AppMemoryUsageIncreased(object sender, object e)
        {
            if (IsInBackgroundMode)
            {
                AppMemoryUsageLevel level = MemoryManager.AppMemoryUsageLevel;

                if (level == AppMemoryUsageLevel.OverLimit || level == AppMemoryUsageLevel.High)
                {
                    ReduceMemoryUsage();
                }
            }
        }
Example #4
0
        /// <summary>
        /// Handle system notifications that the app has increased its
        /// memory usage level compared to its current target.
        /// </summary>
        /// <remarks>
        /// The app may have increased its usage or the app may have moved
        /// to the background and the system lowered the target for the app
        /// In either case, if the application wants to maintain its priority
        /// to avoid being suspended before other apps, it may need to reduce
        /// its memory usage.
        ///
        /// This is not a replacement for handling AppMemoryUsageLimitChanging
        /// which is critical to ensure the app immediately gets below the new
        /// limit. However, once the app is allowed to continue running and
        /// policy is applied, some apps may wish to continue monitoring
        /// usage to ensure they remain below the limit.
        /// </remarks>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MemoryManager_AppMemoryUsageIncreased(object sender, object e)
        {
            // Obtain the current usage level
            AppMemoryUsageLevel level = MemoryManager.AppMemoryUsageLevel;

            // Check the usage level to determine whether reducing memory is necessary.
            // Memory usage may have been fine when initially entering the background but
            // the app may have increased its memory usage since then and will need to trim back.
            if (level == AppMemoryUsageLevel.OverLimit || level == AppMemoryUsageLevel.High)
            {
                // ReduceMemoryUsage(MemoryManager.AppMemoryUsageLimit);
            }
        }
Example #5
0
 public GroupInfoDetails(
     Guid iid, bool shared,
     AppMemoryUsageLevel cLevel, ulong cLimit, ulong pCommit, ulong tCommit,
     AppResourceGroupExecutionState ex, AppResourceGroupEnergyQuotaState eq,
     IList <AppResourceGroupBackgroundTaskReport> tasks, IList <ProcessInfoDetails> p)
 {
     InstanceId         = iid;
     IsShared           = shared;
     CommitUsageLevel   = cLevel;
     CommitUsageLimit   = cLimit;
     PrivateCommitUsage = pCommit;
     TotalCommitUsage   = tCommit;
     ExecutionState     = ex;
     EnergyQuotaState   = eq;
     BgTasks            = tasks;
     Processes          = p;
 }
Example #6
0
        public async static void Update()
        {
            if (processes != null)
            {
                foreach (ProcessDiagnosticInfo process in processes)
                {
                    string exeName = process.ExecutableFileName;
                    string pid     = process.ProcessId.ToString();

                    ProcessCpuUsageReport cpuReport = process.CpuUsage.GetReport();
                    TimeSpan userCpu   = cpuReport.UserTime;
                    TimeSpan kernelCpu = cpuReport.KernelTime;

                    ProcessMemoryUsageReport memReport = process.MemoryUsage.GetReport();
                    ulong npp     = memReport.NonPagedPoolSizeInBytes;
                    ulong pp      = memReport.PagedPoolSizeInBytes;
                    ulong peakNpp = memReport.PeakNonPagedPoolSizeInBytes;
                    //...etc

                    ProcessDiskUsageReport diskReport = process.DiskUsage.GetReport();
                    long bytesRead    = diskReport.BytesReadCount;
                    long bytesWritten = diskReport.BytesWrittenCount;
                    //...etc
                    if (process.IsPackaged)
                    {
                        IList <AppDiagnosticInfo> diagnosticInfos = process.GetAppDiagnosticInfos();
                        if (diagnosticInfos != null && diagnosticInfos.Count > 0)
                        {
                            AppDiagnosticInfo diagnosticInfo = diagnosticInfos.FirstOrDefault();
                            if (diagnosticInfo != null)
                            {
                                IList <AppResourceGroupInfo> groups = diagnosticInfo.GetResourceGroups();
                                if (groups != null && groups.Count > 0)
                                {
                                    AppResourceGroupInfo group = groups.FirstOrDefault();
                                    if (group != null)
                                    {
                                        string      name        = diagnosticInfo.AppInfo.DisplayInfo.DisplayName;
                                        string      description = diagnosticInfo.AppInfo.DisplayInfo.Description;
                                        BitmapImage bitmapImage = await GetLogoAsync(diagnosticInfo);

                                        AppResourceGroupStateReport stateReport = group.GetStateReport();
                                        if (stateReport != null)
                                        {
                                            string executionStatus = stateReport.ExecutionState.ToString();
                                            string energyStatus    = stateReport.EnergyQuotaState.ToString();
                                        }

                                        AppResourceGroupMemoryReport memoryReport = group.GetMemoryReport();
                                        if (memoryReport != null)
                                        {
                                            AppMemoryUsageLevel level = memoryReport.CommitUsageLevel;
                                            ulong limit         = memoryReport.CommitUsageLimit;
                                            ulong totalCommit   = memoryReport.TotalCommitUsage;
                                            ulong privateCommit = memoryReport.PrivateCommitUsage;
                                            ulong sharedCommit  = totalCommit - privateCommit;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
            const int StackLargeTypeSize    = 32;                                                   // If T is larger than this we'll trim an extra (additional) when under high pressure

            internal void Trim(TimeSpan currentTime, AppMemoryUsageLevel usageLevel)
            {
                if (_count == 0)
                {
                    return;
                }

                var trimDelay = usageLevel == AppMemoryUsageLevel.High ? StackHighTrimAfter : StackTrimAfter;

#if !HAS_EXPENSIVE_TRYFINALLY
                lock (this)
#endif
                {
                    if (_count == 0)
                    {
                        return;
                    }

                    if (_timestamp == TimeSpan.Zero)
                    {
                        _timestamp = currentTime;
                        return;
                    }

                    if ((currentTime - _timestamp) <= trimDelay)
                    {
                        return;
                    }

                    var trimCount = StackLowTrimCount;
                    switch (usageLevel)
                    {
                    case AppMemoryUsageLevel.High:
                        trimCount = StackHighTrimCount;

                        // When pressure is high, aggressively trim larger arrays.
                        if (_bufferLength > StackLargeBucket)
                        {
                            trimCount++;
                        }
                        if (SizeOfT > StackModerateTypeSize)
                        {
                            trimCount++;
                        }
                        if (SizeOfT > StackLargeTypeSize)
                        {
                            trimCount++;
                        }
                        break;

                    case AppMemoryUsageLevel.Medium:
                        trimCount = StackMediumTrimCount;
                        break;
                    }

#if TRACE_REUSE
                    Console.WriteLine($"ArrayPool<{typeof(T)}>(bucket:{_buffers.Length} sizeof:{Unsafe.SizeOf<T>()} created:{_created} reused:{_reused}) = {_count}");
#endif

                    while (_count > 0 && trimCount-- > 0)
                    {
                        TrimOne();
                    }

                    _timestamp = _count > 0 ?
                                 _timestamp + TimeSpan.FromMilliseconds((trimDelay.TotalMilliseconds / 4)) :                // Give the remaining items a bit more time
                                 TimeSpan.Zero;
                }
            }
Example #8
0
        private AppInfoDetails CreateDetailsFromDiagnostics(AppRowInfo ari)
        {
            Debug.WriteLine("CreateDetailsFromDiagnostics: aumid={0}, name={1}",
                            ari.Adi.AppInfo.AppUserModelId, ari.Adi.AppInfo.DisplayInfo.DisplayName);

            AppInfoDetails appDetails = null;

            try
            {
                // Create an AppInfoDetails from this AppRowInfo.AppDiagnosticInfo.
                IList <GroupInfoDetails>     groupDetails = new List <GroupInfoDetails>();
                IList <AppResourceGroupInfo> groups       = ari.Adi.GetResourceGroups();
                if (groups != null && groups.Count > 0)
                {
                    foreach (AppResourceGroupInfo group in groups)
                    {
                        Debug.WriteLine("group Id: {0}", group.InstanceId);

                        IList <ProcessInfoDetails>    pDetails = new List <ProcessInfoDetails>();
                        IList <ProcessDiagnosticInfo> pInfos   = group.GetProcessDiagnosticInfos();
                        if (pInfos != null && pInfos.Count > 0)
                        {
                            foreach (ProcessDiagnosticInfo pInfo in pInfos)
                            {
                                TimeSpan kernel = TimeSpan.Zero;
                                TimeSpan user   = TimeSpan.Zero;

                                ulong npp    = 0;
                                ulong pp     = 0;
                                ulong pFault = 0;
                                ulong pFile  = 0;
                                ulong pNpp   = 0;
                                ulong pPP    = 0;
                                ulong ppFile = 0;
                                ulong pVirt  = 0;
                                ulong pWSet  = 0;
                                ulong ppc    = 0;
                                ulong vm     = 0;
                                ulong ws     = 0;

                                long br = 0;
                                long bw = 0;
                                long ob = 0;
                                long oo = 0;
                                long ro = 0;
                                long wo = 0;

                                ProcessCpuUsageReport pcReport = pInfo.CpuUsage.GetReport();
                                if (pcReport != null)
                                {
                                    kernel = pcReport.KernelTime;
                                    user   = pcReport.UserTime;
                                }
                                ProcessMemoryUsageReport pmReport = pInfo.MemoryUsage.GetReport();
                                if (pmReport != null)
                                {
                                    npp    = pmReport.NonPagedPoolSizeInBytes;
                                    pp     = pmReport.PagedPoolSizeInBytes;
                                    pFault = pmReport.PageFaultCount;
                                    pFile  = pmReport.PageFileSizeInBytes;
                                    pNpp   = pmReport.PeakNonPagedPoolSizeInBytes;
                                    pPP    = pmReport.PeakPagedPoolSizeInBytes;
                                    ppFile = pmReport.PeakPageFileSizeInBytes;
                                    pVirt  = pmReport.PeakVirtualMemorySizeInBytes;
                                    pWSet  = pmReport.PeakWorkingSetSizeInBytes;
                                    ppc    = pmReport.PrivatePageCount;
                                    vm     = pmReport.VirtualMemorySizeInBytes;
                                    ws     = pmReport.WorkingSetSizeInBytes;
                                }
                                ProcessDiskUsageReport pdReport = pInfo.DiskUsage.GetReport();
                                if (pdReport != null)
                                {
                                    br = pdReport.BytesReadCount;
                                    bw = pdReport.BytesWrittenCount;
                                    ob = pdReport.OtherBytesCount;
                                    oo = pdReport.OtherOperationCount;
                                    ro = pdReport.ReadOperationCount;
                                    wo = pdReport.WriteOperationCount;
                                }

                                ProcessInfoDetails pDetail = new ProcessInfoDetails(
                                    pInfo.ProcessId, pInfo.ExecutableFileName, pInfo.ProcessStartTime,
                                    kernel, user,
                                    npp, pp, pFault, pFile, pNpp, pPP, ppFile, pVirt, pWSet, ppc, vm, ws,
                                    br, bw, ob, oo, ro, wo);
                                pDetails.Add(pDetail);
                            }
                        }

                        AppMemoryUsageLevel usageLevel = AppMemoryUsageLevel.Low;
                        ulong commitLimit   = 0;
                        ulong privateCommit = 0;
                        ulong totalCommit   = 0;
                        AppResourceGroupExecutionState   ex = AppResourceGroupExecutionState.Unknown;
                        AppResourceGroupEnergyQuotaState eq = AppResourceGroupEnergyQuotaState.Unknown;

                        AppResourceGroupMemoryReport mReport = group.GetMemoryReport();
                        AppResourceGroupStateReport  sReport = group.GetStateReport();
                        IList <AppResourceGroupBackgroundTaskReport> bgReports = new List <AppResourceGroupBackgroundTaskReport>();
                        bgReports = group.GetBackgroundTaskReports();

                        if (mReport != null)
                        {
                            usageLevel    = mReport.CommitUsageLevel;
                            commitLimit   = mReport.CommitUsageLimit;
                            privateCommit = mReport.PrivateCommitUsage;
                            totalCommit   = mReport.TotalCommitUsage;
                        }
                        if (sReport != null)
                        {
                            ex = sReport.ExecutionState;
                            eq = sReport.EnergyQuotaState;
                        }
                        GroupInfoDetails groupDetail = new GroupInfoDetails(
                            group.InstanceId, group.IsShared,
                            usageLevel, commitLimit, privateCommit, totalCommit,
                            ex, eq,
                            bgReports, pDetails);
                        groupDetails.Add(groupDetail);
                    }

                    // We'll save time and get the cached Logo from the ARI, and get the rest of the data from the ADI.
                    appDetails = new AppInfoDetails(
                        ari.Logo,
                        ari.Adi.AppInfo.AppUserModelId, ari.Adi.AppInfo.Id, ari.Adi.AppInfo.PackageFamilyName,
                        ari.Adi.AppInfo.DisplayInfo.DisplayName, ari.Adi.AppInfo.DisplayInfo.Description,
                        groupDetails);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
            return(appDetails);
        }