我有许多连接到它的webservice。 我用这个代码:如何在ASP.NET webservice中执行SQL事务异步
IAsyncResult result = sqlCommand.BeginExecuteNonQuery();
while (!result.IsCompleted)
{
System.Threading.Thread.Sleep(500);
}
sqlCommand.EndExecuteNonQuery(result);
我觉得这不是一个最好的方法,因为我叫Sleep()
。 PS。这种方法将是Web Service与服务器
UPDATE2的减速性能: 我试着描述我的代码更多: 我有Web客户端和2个事件(ProgressChanged
和DownloadCompleted
)
[WebMethod]
public void DonwloadFromRemoteServer(string uniqueId, string url)
{
if (!Directory.Exists(uniqueId))
Directory.CreateDirectory(uniqueId);
WebClient wc = new WebClient();
wc.DownloadProgressChanged += (sender, args) => wc_DownloadProgressChanged(sender, args, uniqueId, Path.GetFileName(url));
wc.DownloadFileCompleted += (sender, args) => wc_DownloadFileCompleted(sender, args, uniqueId, Path.GetFileName(url));
wc.DownloadFileAsync(new Uri(url), String.Format("{0}\\{1}", uniqueId, Path.GetFileName(url)));
}
void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e, string uniqueId, string fileName)
{
SqlConnection connection = new SqlConnection("Data Source=.\\SQLSERVER;Initial Catalog=XRingtoneDB;Integrated Security=True;Asynchronous Processing=true");
connection.Open();
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Connection = connection;
sqlCommand.CommandText = String.Format("IF NOT EXISTS(SELECT uniqueId FROM downloads WHERE uniqueID = '{0}') " +
"INSERT INTO downloads VALUES ('{0}', '{1}', '{2}') " +
"IF EXISTS(SELECT uniqueId FROM downloads WHERE uniqueID = '{0}') " +
"Update downloads " +
"set progress='{2}' " +
"where uniqueId='{0}' ", uniqueId, fileName, e.BytesReceived);
AsyncCallback callback = ((result) =>
{
sqlCommand.EndExecuteNonQuery(result);
connection.Close();
});
sqlCommand.BeginExecuteNonQuery(callback, sqlCommand);
}
void wc_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e, string uniqueId, string fileName)
{
SqlConnection connection = new SqlConnection("Data Source=.\\SQLSERVER;Initial Catalog=XRingtoneDB;Integrated Security=True;Asynchronous Processing=true");
connection.Open();
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Connection = connection;
sqlCommand.CommandText = String.Format("update downloads " +
"set progress='Completed' " +
"where uniqueId='{0}' and fileName='{1}'", uniqueId, fileName);
AsyncCallback callback = ((result) =>
{
sqlCommand.EndExecuteNonQuery(result);
sqlCommand.Connection.Close();
});
sqlCommand.BeginExecuteNonQuery(callback, sqlCommand);
}
ProgressChanged
工作正常但DownloadCompleted
只能在调试模式下工作。 我认为这是因为我需要暂停或在这些调用之间等待。
Update3: 有时我在执行下载后有两个相同的行在数据库中! 困惑 我是否需要关闭所有连接?
我知道它。但是如何?请参阅更新中的问题。 – TheX
@TheX:我已经用附加信息更新了答案。 –
你看到我的更新吗?我使用你的方法,但我的第二个查询(当调用DonwloadCompleted())没有运行。我想到了同步方法,但我不确定。如果1000个用户一次调用查询? – TheX