0

I have the following wrapper helper class that I use for MarkDown.

public static class MarkdownHelper
{
    static Markdown _MarkdownTransformer;

    static MarkdownHelper()
    {
        _MarkdownTransformer = new Markdown( new MarkdownOptions { AutoNewLines = true, AutoHyperlink = true, StrictBoldItalic = true } );
    }

    public static IHtmlString Markdown(this HtmlHelper helper, string text)
    {
        string html = _MarkdownTransformer.Transform(text);

        return new MvcHtmlString(html);
    }
}

This only seems to be able to generate (once in a few times) an Exception on first hit:

System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.

at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
at MarkdownSharp.Markdown.FormParagraphs(String text)
at MarkdownSharp.Markdown.RunBlockGamut(String text)
at MarkdownSharp.Markdown.Transform(String text)
at AppExtensions.MarkdownHelper.Markdown(HtmlHelper helper, String text)
[...]

It seems to me like a concurrency problem. I'm using the latest stable version of MarkDownSharp.

Do I need to a different pattern for the wrapper class?

Dirk Boer
  • 8,522
  • 13
  • 63
  • 111

1 Answers1

1

The most likely problem is that you are using a single transformer in different threads. As one thread starts transforming, another one clears out the transformers state and it throws up. I did this too.. Oy.

One way to resolve this is just to mark the transformer "thread static" and initialize it in a property (because initializing thread statics only works once inline). Here is how that looks, just make sure to use the property not the static variable directly.

[ThreadStatic] private static Markdown _markdownTransformer;

    private static Markdown Transformer
    {
        get
        {
            if (_markdownTransformer == null)
            {
                _markdownTransformer = new Markdown(new MarkdownOptions
                {
                    /*your options here*/
                });
            }

            return _markdownTransformer;
        }
    }
James White
  • 2,062
  • 2
  • 24
  • 36