C# 中异步调用 SQL Server 存储过程
是否可以通过 C# 异步调用 SQL Server 存储过程?
我有一个存储过程,它写入特定数据库的备份(这可能需要很长时间才能完成),并且我想在 Windows 窗体中显示备份过程的进度(为此,我使用 http://www.wisesoft.co.uk/articles/tsql_backup_restore_progress.aspx)。或者我应该使用Backgroundworker控件并在后台作业(自己的线程)中运行SP?
Is it possible to call a SQL Server stored procedure asynchronously via C#?
I have a stored procedure which writes a backup of a specific database (this can take a long time to complete) and I want to show the progress of the backup process in a windows forms (for this I use http://www.wisesoft.co.uk/articles/tsql_backup_restore_progress.aspx). Or should I use the Backgroundworker control and run the SP in a backgroundjob (own thread) ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在
SqlCommand
中,您可以使用BeginExecuteNonQuery
和EndExecuteNonQuery
异步运行命令。后者将阻塞直到完成。但是,这不会报告服务器有关备份进展情况的进度 - 我会使用选框进度条。为了避免 EndExecuteNonQuery 阻塞您的 UI(取决于您如何处理它),您将需要一个后台线程。如果您使用此方法,那么您最好不要使用
BeginXXX
EndXXX
方法并在后台线程上同步执行 -BackgroundWorker
最适合此目的。为了避免在 UI 中使用后台线程,您需要注册一个回调并处理生成的事件(在此事件处理程序中调用
EndXXX
,但不是在EndXXX
上阻塞)它会立即返回)。更新:根据评论,对于异步调用 SQL 命令/连接内容,您需要在连接字符串中指定尽可能多的内容:
http://www.connectionstrings.com/sql-server-2008
或者在使用连接字符串生成器的代码中:
In your
SqlCommand
you can run commands asynchronously usingBeginExecuteNonQuery
andEndExecuteNonQuery
. The latter will block until its done. However this won't report the progress from the server about how the backup is going - I'd use a marquee progress bar for it.To avoid the
EndExecuteNonQuery
from blocking your UI (depending on how you handle it), you will need a background thread. If you use this then you may as well not useBeginXXX
EndXXX
methods and do it synchronously on a background thread - theBackgroundWorker
is best for this.To avoid using a background thread in the UI, instead of blocking on
EndXXX
you will need to register a callback and handle the resulting event (callingEndXXX
in this event handler, but it will return immediately).Update: as per a comment, for asynchronous calls into the SQL command/connection stuff, you need to specify as much in the connection string:
http://www.connectionstrings.com/sql-server-2008
Or in code using the connection string builder:
无论如何,我都会在一个单独的线程中完成它,所以我可能会采用BackgroundWorker方法。
I would have done it in a separate thread anyway, so I would probably go for the BackgroundWorker approach.