开发者

key already added for dictionary - thread problem?

I need some help getting my head around thread safety and dictionaries. When adding to a dictionary I get an error saying "An item with the same key has already been added" (when I开发者_高级运维 say I get it, I haven't actually been able to replicate this but have seen it in the error logs).

From what I can see when reading similar questions it's likely to have something to do with thread safety, but I'm still not clear on what's happening. And as it's hard to test, especially when I can't replicate it, I'm hoping that someone might be able to explain or point me in the right direction. It's an asp.net web application (C#), and the error is happening when getting a quiz tailored for the specific user. I'm also getting errors trying to accessing keys that doesn't exist, but one thing at a time!

I've made a mini example where I've stripped out everything I didn't think was necessary to show the problem. If I've stripped out too much let me know.

public class QuizDataAdapterFactory
{
    private static IQuizDataAdapter q_adapter = new MyQuizDataAdapter();

    public static IQuizDataAdapter Create()
    {
        return q_adapter;
    }
}

IQuizDataAdapter dataAdapter = QuizDataAdapterFactory.Create();

public class MyQuizDataAdapter : IQuizDataAdapter
{
    private Quiz quiz;

    public Quiz GetQuiz()
    {
        quiz = new Quiz();
        quiz.QuestionIndex = new Dictionary<Guid, QuestionBase>();

        GetQuestions();

        return quiz;
    }

    private void GetQuestions()
    {
        Item[] items;

        foreach (Item questionItem in items)
        {
            Question newQuestion = new Question();
            PopulateQuestionFromItem(newQuestion, questionItem);
            questions.Add(newQuestion);

            // this is where it fails
            quiz.QuestionIndex.Add(questionItem.ID.ToGuid(), newQuestion);
        }
    }
}

Would adding [ThreadStatic] for the IQuizDataAdapter do the trick?

Thanks,

Annelie


You're only ever creating one instance of MyQuizDataAdapter due to your Create method being completely inappropriately named - it doesn't "create" an adapter, it returns the same one every time!

Create a different one each time instead, and you'll at least be in a better position... admittedly I don't much like the way that every time you call GetQuiz it repopulates the quiz in MyQuizDataAdapter too, but that's another step...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜