gpt4 book ai didi

c# - 在 C# 中处理静态字段内存泄漏的最佳实践

转载 作者:太空宇宙 更新时间:2023-11-03 13:36:19 26 4
gpt4 key购买 nike

我应该为用户的当前实例创建一个上下文对象,代码是

 public class WorkoutContext {
protected static WorkoutContext mWorkoutContext ;
protected WorkOut mWorkOut;

protected WorkoutContext(WorkOut workout)
{
mWorkOut= workout;
}

public static WorkoutContext CreateContext(WorkOut workout))
{
if (mWorkoutContext == null)
{
mWorkoutContext = new WorkoutContext (form);
}
else
{
if (workout != mWorkoutContext.WorkOut)
{
mWorkoutContext = new WorkoutContext (workout);
}
}
return mWorkoutContext ;
}
}

在并发环境中,它会为每个用户创建一个 WorkOutContext 实例,但不会在请求过程完成后释放该实例。为了克服这个问题修改了 CreateContext 方法如下

public class WorkoutContext {
protected WorkoutContext mWorkoutContext ;
protected WorkOut mWorkOut;

protected WorkoutContext(WorkOut workout)
{
mWorkOut= workout;
}

public static WorkoutContext CreateContext(WorkOut workout))
{
return new WorkoutContext(workout);
}
}

是否有任何其他方法可以实现同一 WorkOut 实例只有一个 WorkoutContext 实例。

最佳答案

尝试这样的事情:

public class WorkoutContext {
protected WorkOut mWorkOut;
private static Dictionary<WorkOut, WorkoutContext> dic = new ...;
private static object lockObj = new object();

protected WorkoutContext(WorkOut workout)
{
mWorkOut= workout;
}

public static WorkoutContext CreateContext(WorkOut workout)
{
lock(lockObj) {
if (dic.ContainsKey(workout))
return dic[workout];
var wc = new WorkoutContext(workout)
dic.Add(workout, wc);
return wc;
}
}
}

关于c# - 在 C# 中处理静态字段内存泄漏的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18630665/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com