我有許多連接到它的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