如何解决关于 .NET 中的内存泄漏,使用不在 Func 参数列表中的对象的 Func 回调
我在下面有一个回调函数,它采用 public void onIabSetupFinished(IabResult result) {
if (result.isSuccess()) {
iabHelper.queryInventoryAsync(false,this);
} else {
showError("err");
}
}
的一个参数。我还有一些来自调用父函数的其他函数。参数 name
、otherGame
等是否会导致任何类型的内存泄漏或性能问题,或者这是有效的编程设置?
_venueLocationsManager
回调来自
private IEnumerable<ValidateScheduleResult> GetMinimumOverlappingPoolGames(EventScheduleGameLayout gridItem,EventScheduleGameLayout otherGame,EventScheduleTeamLayout otherTeam,int minimumTimeBetweenGames,ValidationScheduleSettingsModel scheduleSettings)
{
Func<string,ValidateScheduleResult> callback = (name) =>
{
return FillGameinformation(new ValidateMinimumTimeBetweenGamesResult(name,otherGame.GetDate(),otherGame.GetTime(),_venueLocationsManager.GetVenueLocationName(otherGame.VenueCourtId),minimumTimeBetweenGames,scheduleSettings.ContestType),gridItem,ValidateItemResult.StatusType.Warning);
};
return GetoverlappingPoolGames(gridItem,otherTeam,callback);
}
private IEnumerable<ValidateScheduleResult> GetoverlappingPoolGames(EventScheduleGameLayout gridItem,Func<string,ValidateScheduleResult> callback)
{
var validationScheduleResults = new List<ValidateScheduleResult>();
Action<string> nameCallback = (name) =>
{
validationScheduleResults.Add(callback(name));
};
_eventScheduleValidatoRSService.PoolGamesValidator.IsPoolGamesRestricted(gridItem.Matchup.AwayTeam,nameCallback);
_eventScheduleValidatoRSService.PoolGamesValidator.IsPoolGamesRestricted(gridItem.Matchup.HomeTeam,nameCallback);
if (gridItem.Matchup.WorkTeam != null)
{
_eventScheduleValidatoRSService.PoolGamesValidator.IsPoolGamesRestricted(gridItem.Matchup.WorkTeam,nameCallback);
}
foreach (var validationResult in validationScheduleResults)
yield return validationResult;
}
IsPoolGameRestricted
if (scheduleSettings.MinimumTimeBetweenGames.HasValue)
{
// Get Division Teams And Teams Cross Playing
var minimumTimesBetween = GetMinimumTimeBetweenRow(scheduledMatchups,scheduleSettings.MinimumTimeBetweenGames.Value,gridItem.GameDuration,gridItem).Where(q => q != gridItem && (q.Matchup.DivisionId == gridItem.Matchup.DivisionId || ScheduleHelper.HasTeamGame(q.Matchup,gridItem.Matchup) || ScheduleHelper.HasSeededGame(q.Matchup,gridItem.Matchup))).ToList();
foreach (var divisionGame in minimumTimesBetween)
{
validationResults.AddRange(GetMinimumOverlappingPoolGames(gridItem,divisionGame,divisionGame.Matchup.AwayTeam,scheduleSettings));
validationResults.AddRange(GetMinimumOverlappingPoolGames(gridItem,divisionGame.Matchup.HomeTeam,scheduleSettings));
}
}
解决方法
这不会导致任何内存泄漏,因为 .NET 运行时将为您管理内存分配,并确保只要这些对象仍在使用中,它们就不会被清除。
https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/
对于使用回调和直接调用函数的性能来说,即使不一样,也应该非常相似。
作为旁注,您可能还想看看使用 async/await,而不是依赖回调来延迟执行,它提供了一种替代方案,并且可以说是更易于阅读的解决方案。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。