无法从BackgroundWorker调用存储过程
问题描述:
我在ASP.NET MVC中,并且(主要)使用实体框架。我想调用一个存储过程而不用等待它完成。我目前的做法是使用后台工作人员。麻烦的是,它在没有使用后台工作的情况下工作正常,但无法执行。
在DoWork事件处理程序中,当我调用 command.ExecuteNonQuery(); 它只是“消失”(在调试模式下永远不会进入下一行)。 任何人都有异步调用sproc的提示?顺便说一句,如果这很重要的话,它将成为SQL Azure的产品;现在为SQL Server 2008.无法从BackgroundWorker调用存储过程
public void ExecAsyncUpdateMemberScoreRecalc(MemberScoreRecalcInstruction instruction)
{
var bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(AsyncUpdateMemberScoreRecalc_DoWork);
bw.WorkerReportsProgress = false;
bw.WorkerSupportsCancellation = false;
bw.RunWorkerAsync(instruction);
}
private void AsyncUpdateMemberScoreRecalc_DoWork(object sender, DoWorkEventArgs e)
{
var instruction = (MemberScoreRecalcInstruction)e.Argument;
string connectionString = string.Empty;
using (var sprocEntities = new DSAsyncSprocEntities()) // getting the connection string
{
connectionString = sprocEntities.Connection.ConnectionString;
}
using (var connection = new EntityConnection(connectionString))
{
connection.Open();
EntityCommand command = connection.CreateCommand();
command.CommandText = DSConstants.Sproc_MemberScoreRecalc;
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue(DSConstants.Sproc_MemberScoreRecalc_Param_SageUserId, instruction.SageUserId);
command.Parameters.AddWithValue(DSConstants.Sproc_MemberScoreRecalc_Param_EventType, instruction.EventType);
command.Parameters.AddWithValue(DSConstants.Sproc_MemberScoreRecalc_Param_EventCode, instruction.EventCode);
command.Parameters.AddWithValue(DSConstants.Sproc_MemberScoreRecalc_Param_EventParamId, instruction.EventParamId);
int result = 0;
// NEVER RETURNS FROM RUNNING NEXT LINE (and never executes)... yet it works if I do the same thing directly in the main thread.
result = command.ExecuteNonQuery();
}
}
答
在调用中添加一个try catch,看看是否有任何异常被捕获并因此中止该线程。
try {
result = command.ExecuteNonQuery();
} catch(Exception ex) {
// Log this error and if needed handle or
throw;
}
这么简单,但如此真实......我在外面尝试了一下,但是由于某些原因,它从来没有冒出来。事实证明这是一些基本的东西,所以上面的代码确实可以做到这一点。对于那些希望使用EF来做到这一点的人,我需要做的另一件事是使用单独的edmx文件,并且只能从异步线程调用它。 – Vince 2010-11-04 11:51:48