简体   繁体   中英

Entity Framework causing issue using Multithreading (Task) in C#

Inside my Asp.net MVC 3 app, using Entity Framework 6.0, I am trying to update a database table record using an asynchronous method like:

public static async Task UpdateAssetLogAsync(string assetID)
{
    using (var context = new MyContext())
    {
        var log = await context.UploadedLogs.SingleAsync(e => e.AssetID == assetID);
        if (log != null)
        {
            log.LastUpdatedOn = DateTime.Now;
            await context.SaveChangesAsync();
        }
    }
}

Unfortunately code execution stops as soon as it comes to line number 5 ie

var log = await context.UploadedLogs.SingleAsync(e => e.AssetID == assetID);

Visual Studio (2012) shows no error at all and program execution just breaks from here.

Please can anyone tell what is the issue?

[Edit] This is my connection string

<add name="MyContext" connectionString="Server=.\SQLExpress;Database=Test;Max Pool Size=80;Integrated Security=true;MultipleActiveResultSets=True" providerName="System.Data.SqlClient"/>

[Edit] This is happening because of 'Integrated Security=true' within connection string. If I use sa and password options in connection string it works fine. In my web.config an impersonation context is already defined which works fine outside Task but inside Task it seems the impersonation context is not available, causing EF not to connect.

Threads spawned with async methods usually return a Task or Task<TResult> . Unfortunately, the impersonation context of the caller is not passed along to this thread - by default. That may be why you can't connect to the DB - wrong credentials.

You can pass the impersonation context through aspnet.config file settings using the <alwaysFlowImpersonationPolicy> in IIS

OR

Within your code, use WindowsIdentity and WindowsImpersonationContext to allow Impersonation context to flow with the async thread.

Here are a few articles of interest:

http://blog.codeishard.net/2012/09/17/await-async-mvc-and-impersonation/

How do I set the user identity for tasks when calling Task.WaitAll()?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM