I need to call a stored proc that does quite a bit of work.
I want to be able to "fire and forget" e.g not wait for the response of the stored proc before moving onto the next record as that slows things down and I need to be moving quickly.
What is the best method of calling a stored proc in C# and NOT waiting for the result, returning a success status, and then moving onto the next record.
I'd like to be able to just quickly loop through my object list of selections and call some method that does the DB call without waiting for the response before moving to the next item in the loop.
It's using C# 4.5.
I was thinking about using something like
Parallel.ForEach(sqlRecordset.AsEnumerable(), recordsetRow =>
{
// get data for selection
// call DB to save without waiting for response / success/failure status
}
But I don't know if this is the best approach or not.
Ideas?
Thanks in advance for any help.
Use only the correct number of columns you need When you code all queries with SELECT, you pull off more data than you need. So here's how to make the SELECT query faster: before doing a SELECT, make sure you have the correct number of columns against as many rows as you want. This will speed up your processes.
There are a number of things that may cause a query to take longer time to execute: Inefficient query – Use non-indexed columns while lookup or joining, thus MySQL takes longer time to match the condition. Table lock – The table is locked, by global lock or explicit table lock when the query is trying to access it.
The query wait option specifies the time, in seconds (from 0 through 2147483647), that a query waits for resources before it times out. The default value for this option is -1. This means the time-out is calculated as 25 times the estimated query cost.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With