run database query and not wait for result run database query and not wait for result database database

run database query and not wait for result


Parallel.ForEach is parallel but synchronous - it will wait for all its iterations to finish.

You may use TPL (Task Parallel Library) to achieve what you want:

foreach (var recordsetRow_doNotUse in sqlRecordset.AsEnumerable()){    var recordsetRow = recordsetRow_doNotUse;    Task.Run(() => {         Console.WriteLine(recordsetRow);        /* or do whatever you want with it here */     });}

Task.Run returns a task so if you need to do something when all of them are done you can put all of them in an array and then use Task.WhenAll to obtain a Task which will be complete when all iterations are complete, without blocking any threads.

P.S. I don't know what you mean by C# 4.5, probably .NET 4.5 which is C# 5. My sample code above won't work with earlier versions of C#.


The easier approach is using ADO.NET:

var cmd = new SqlCommand("storeProcName", sqlConnection);cmd.CommandType = CommandType.StoredProcedure;cmd.BeginExecuteNonQuery();


Since you would like to iterate through each records, get some values and store it in the database and not wait for any record set, you could do something like below; Assuming you are using windows application and know threading;

foreach (DataRow row in DataTable.Rows) //you can use any enumerable object here{    string s = row.Fields("name").ToString();    Thread t = new Thread(new ParameterizedThreadStart(SaveName));    t.IsBackground = true;    t.start(s);}public void SaveName(object s){    //your code to save the value in 's'}

This way, you will not have to wait for the database to respond and every values will be saved. The threads will be destroyed as soon as it finish saving and processing your records..

Hope this helps.

Happy coding..!!