2

On my small project, I try to save some data or send notification to users.

Could I use await/async on my c# code and query run even after sending data to client ?

Here is the sample:

async string GetName(long userId)
{
string information="";  // loading data with entity

await Task.Run(() => UpdateActivity(userId));
await Task.Run(() => SendNotification(userId));


return information;
}

void UpdateActivity(long userId)
{
// loading data with entity
// updating activity
}

void SendNotification(long userId)
{
// loading data with entity
// Sending Notification
}

Here is one of my problem during loading data with entity

An exception of type 'System.Data.Entity.Core.EntityException' occurred in mscorlib.dll but was not handled in user code

Additional information: The underlying provider failed on Open.

Entity code, works fine when I haven't using await-async

3
  • 5
    The code you've posted has nothing to do with the exception you're getting. An answer is already here and here on SO and here on codeproject. Commented Sep 19, 2017 at 9:50
  • 4
    @m.rogalski question is about way of using await-async during using entity , entity code works fine when it hasn't await-async Commented Sep 19, 2017 at 9:59
  • What happens inside UpdateActivity, esp. which context instance is used there? Commented Sep 19, 2017 at 10:21

3 Answers 3

2

Let's try this

async Task<string> GetName(long userId)
{
string information="";  // loading data with entity

await Task.Run(() => UpdateActivity(userId));
await Task.Run(() => SendNotification(userId));


return information;
}

Return Task, not string

Sign up to request clarification or add additional context in comments.

Comments

0

Maybe try

await Task.Run(() => UpdateActivity(userId)).ConfigureAwait(false);
await Task.Run(() => SendNotification(userId)).ConfigureAwait(false);

This will make GetName function to stay in the same context.

Also, if create DbContext outside GetName function, it can be disposed before execution of UpdateActivity and SendNotification, since you cannot await GetName. For that you need to return Task, as Dan suggested

Comments

0

I think thats is because dbContext is not available in parallel task as you have passed only userId to parallel task which ultimately refer to dbcontext to perform dbOperation. You need to change architecture for this.

async Task<string> GetName(long userId)
{
string information="";  // loading data with entity
DbContext context = _context// Your dbContext
await Task.Run(() => UpdateActivity(userId, context));


return information;
}

void UpdateActivity(int userId, DbContext context)
{
   //perform dboperation with context
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.