У меня есть веб-сервис со многими подключениями к нему.
Я использовал этот код:
IAsyncResult result = sqlCommand.BeginExecuteNonQuery();
while (!result.IsCompleted)
{
System.Threading.Thread.Sleep(500);
}
sqlCommand.EndExecuteNonQuery(result);
Я думаю, что это не лучший метод, потому что я называю Sleep()
.
PS. Этот метод будет замедлять производительность WebService и сервера
UPDATE2:
я пытаюсь описать мой код больше:
у меня есть WebClient и 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:
Иногда у меня есть две одинаковые строки в БД после выполнения загрузки! смущенно
И нужно ли было закрывать все соединения?