2

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

 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实例。

4

1 回答 1

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;
        }
    }
}
于 2013-09-05T08:05:40.453 回答