我有一个存储过程,该过程将VARCHAR(160)作为存储过程的输出参数。

当我使用executenonquery时,一切正常,我总是会收回预期值。

但是,一旦我切换到使用BegineXecutenonquery,我将获得输出的空值。

我正在使用connstring +“异步处理= true;”在这两种情况下。

可悲的是,在我的情况下,BegineXecutenonQuery的速度快1.5倍...但是我确实需要输出参数。

谢谢!

编辑:这就是我处理BegineXecutenonQuery回调的方式(我使用.NET 4.0 ...)

    Dim resp as String=""
    cmd.BeginExecuteNonQuery(Sub(result As IAsyncResult)
                                 Dim c As SqlCommand = Nothing
                                 Try
                                     c = CType(result.AsyncState, SqlCommand)
                                     c.EndExecuteNonQuery(result)
                                     **resp = CStr(c.Parameters("@response").Value)**
                                 Catch ex As Exception
                                     WriteLog("ERR - LogRequest - " & ex.Message)
                                 Finally
                                     c.Connection.Close()
                                     c.Dispose()
                                 End Try
                             End Sub, cmd)
有帮助吗?

解决方案

如果您使用BegineXecutenonQuery,您的代码将不等待查询在继续之前执行,这就是为什么您没有输出参数的原因。为了检索OUT参数,您需要指定查询完成执行后运行的Asynccallback委托。您是否确定BegineXecutenonQuery确实更快,并且感知到的性能提高不仅仅是因为该过程不在等待查询执行。异步查询的目的是您要启动长时间的处理,例如生成复杂的报告,然后在完成后稍后做些事情,例如,通过电子邮件将用户发送电子邮件告诉他们他们的报告已被处理。

其他提示

当您使用时 BeginExecuteNonQuery 查询在后台运行,您的代码继续运行。可能发生的事情是,您正在查询完成执行之前先查看结果。这是来自MSDN帮助 BeginExecuteNonQuery:

IAsyncResult result = command.BeginExecuteNonQuery();
while (!result.IsCompleted)
{
    Console.WriteLine("Waiting ({0})", count++);
    // Wait for 1/10 second, so the counter
    // does not consume all available resources 
    // on the main thread.
    System.Threading.Thread.Sleep(100);
}
Console.WriteLine("Command complete. Affected {0} rows.", 
     command.EndExecuteNonQuery(result));

因此,结果仅适当可用 IsCompleted 是真的。

请注意,这只是文档中的一个示例,异步函数的真正使用是允许您的应用程序的其余部分(例如UI)继续运行,同时正在运行长时间的查询。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top