C# 中异步调用 SQL Server 存储过程

发布于 2024-09-10 17:47:31 字数 332 浏览 5 评论 0原文

是否可以通过 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

伴我老 2024-09-17 17:47:31

SqlCommand 中,您可以使用 BeginExecuteNonQueryEndExecuteNonQuery 异步运行命令。后者将阻塞直到完成。但是,这不会报告服务器有关备份进展情况的进度 - 我会使用选框进度条。

为了避免 EndExecuteNonQuery 阻塞您的 UI(取决于您如何处理它),您将需要一个后台线程。如果您使用此方法,那么您最好不要使用 BeginXXX EndXXX 方法并在后台线程上同步执行 - BackgroundWorker 最适合此目的。

为了避免在 UI 中使用后台线程,您需要注册一个回调并处理生成的事件(在此事件处理程序中调用 EndXXX,但不是在 EndXXX 上阻塞)它会立即返回)。

更新:根据评论,对于异步调用 SQL 命令/连接内容,您需要在连接字符串中指定尽可能多的内容:

http://www.connectionstrings.com/sql-server-2008

Server=myServerAddress; Database=myDataBase; Integrated Security=True; Asynchronous Processing=True;

或者在使用连接字符串生成器的代码中:

builder.AsynchronousProcessing = true;

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.

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.

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).

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;

Or in code using the connection string builder:

builder.AsynchronousProcessing = true;
So要识趣 2024-09-17 17:47:31

无论如何,我都会在一个单独的线程中完成它,所以我可能会采用BackgroundWorker方法。

I would have done it in a separate thread anyway, so I would probably go for the BackgroundWorker approach.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文