Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save Records in Database asynchronously Or Parallely in .net c#

I have a service in which i have to save a large number of records to database after getting from an API. At the same time i have to return those records to from service to the caller. But problem is that i saving records in DB is taking long time so Service is getting slow. I have searched about this and found some conecept of Parallel task OR async & await.

I am new to this concept and getting confused in its usage

I looked into :

Running multiple C# Task Async http://msdn.microsoft.com/en-us/library/hh191443.aspx

But i am not getting what to do.Please help me:

below is code:

public List<SearchedItems> SearchItems(string ItemToSearch, string AuthenticationToken)
{
    var _list= getRecords from Api //100 records    

     //Task<int>.Factory.StartNew(() => _objBLLNutritionLog.FillNutritionTable(_tempList)); // also tried this

    saveToDb(_list); // need to run this asynchronously Or parallel (Taking long time)

    return _list;

}

i want to return result to caller and on other side want to fill db. Please suggest.

Thank you

like image 574
Gurmeet Avatar asked Dec 27 '13 11:12

Gurmeet


1 Answers

I hope you are using .NET 4.5.

So let's get started. First mark your SearchItems function with async:

public async List<SearchedItems> SearchItems(string ItemToSearch, string AuthenticationToken)
{
}

Then you can await for saveToDb task:

var result = await Task.Factory.StartNew(()=> saveToDb(_list));
like image 138
Xelom Avatar answered Oct 18 '22 04:10

Xelom