一个SQL Server存储过程在C#异步调用 [英] Asynchronous call of a SQL Server stored procedure in C#
问题描述
通过C#是有可能的调用SQL Server存储过程异步?
Is it possible to call a SQL Server stored procedure asynchronously via C#?
我有一个存储过程,它写了一个特定数据库的备份(这可能需要很长的时间才能完成),我想显示备份过程在Windows窗体的进步(为了这个,我用的 http://www.wisesoft.co.uk/articles/tsql_backup_restore_progress.aspx )。或者我应该使用的BackgroundWorker控制和运行在backgroundjob(自己的线程)的SP?
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) ?
推荐答案
在你的的SqlCommand
您可以异步运行使用命令 BeginExecuteNonQuery的
和 EndExecuteNonQuery
。后者将被阻塞,直到其完成。然而,这不会报告从关于备份是怎么回事服务器的进展 - 我会使用一个帐篷进度条就
In your SqlCommand
you can run commands asynchronously using BeginExecuteNonQuery
and EndExecuteNonQuery
. 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.
要避免 EndExecuteNonQuery
阻塞你的UI(取决于你如何处理它),你需要一个后台线程。如果使用,那么你可能也不会使用的BeginXXX
EndXXX
的方法和做同步在后台线程 - 的的BackgroundWorker
是最适合这个。
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 use BeginXXX
EndXXX
methods and do it synchronously on a background thread - the BackgroundWorker
is best for this.
要避免使用,而不是阻塞在 EndXXX
,你需要注册一个回调并处理所产生的事件后台线程的用户界面,(叫 EndXXX
在此事件处理程序,但它会立即返回)。
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 (calling EndXXX
in this event handler, but it will return immediately).
更新:作为每一个注释,异步调用到SQL命令/连接东西,你需要指定尽可能多的连接字符串中:
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
Server=myServerAddress; Database=myDataBase; Integrated Security=True; Asynchronous Processing=True;
还是在code。使用连接字符串生成器:
Or in code using the connection string builder:
builder.AsynchronousProcessing = true;
这篇关于一个SQL Server存储过程在C#异步调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!