我应该为用户的当前实例创建一个上下文对象,代码是
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);
}
}
是否有任何其他方法可以为同一个WorkoutContext
实例只有一个WorkOut
实例。
答案 0 :(得分:1)
尝试这样的事情:
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;
}
}
}