System.Threading.Tasks.Task generating SPException

-1

While using System.Threading.Tasks.Task in my code,I am getting the below exception:

SPException: Attempted to make calls on more than one thread in single threaded mode. (Exception from HRESULT: 0x80010102 (RPC_E_ATTEMPTED_MULTITHREAD))

Please point out in which all cases this exception gets generated.

c#
multithreading
sharepoint
asked on Stack Overflow Jun 29, 2016 by dev • edited Jun 29, 2016 by RenĂ© Vogt

1 Answer

0

You can run only a single thread per context. If you need to multi-thread SharePoint objects, you may use the following snipped as a reference:

public static class SPListItemContextIsolatedExtension 
{
    public static SPListItem Isolate(SPListItem item)
    {
        var parentWeb = item.ParentList.ParentWeb.Url;
        var site = new SPSite(parentWeb);
        var web = site.OpenWeb();
        return web.GetListItem($"{parentWeb}/{item.Url}");
    }

    public static void RunIsolated(this SPListItem item, Action<SPListItem> act)
    {
        Task.Factory.StartNew(() => act(item.Isolate()));
    }
}

Then, you can execute the action calling the extension, such as:

    item.RunIsolated(YourMethodHere);

There might be several other ways to do the isolation, the piece of code above is just an example.

answered on Stack Overflow Jul 21, 2016 by xWaLL • edited Jul 21, 2016 by xWaLL

User contributions licensed under CC BY-SA 3.0