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

Asynchronous call of a SQL Server stored procedure in C#(C#中SQL Server存储过程的异步调用)
本文介绍了C#中SQL Server存储过程的异步调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过 C#异步调用 SQL Server 存储过程?

我有一个存储过程,它写入特定数据库的备份(这可能需要很长时间才能完成),我想在 Windows 窗体中显示备份过程的进度(为此我使用 http://www.wisesoft.co.uk/articles/tsql_backup_restore_progress.aspx).或者我应该使用 Backgroundworker 控件并在后台作业(自己的线程)中运行 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 中,您可以使用 BeginExecuteNonQueryEndExecuteNonQuery 异步运行命令.后者将阻塞直到完成.但是,这不会从服务器报告有关备份进展情况的进度 - 我会使用字幕进度条.

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.

为避免在 UI 中使用后台线程,而不是在 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;

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

Or in code using the connection string builder:

builder.AsynchronousProcessing = true;

这篇关于C#中SQL Server存储过程的异步调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)