[참고] 비동기실행(BeginExecuteNonQuery) - 다중 처리
.NET프로그래밍/ADO.NET 2009. 9. 28. 10:34 |- 동기식(Synchronous) : 하나만 처리
- 비동기식(Asynchronous) : 다중 처리(멀티스레드), AJAX
- 비동기식(Begin ~ End문이 들어가 있음.)
------------------------------------------------------------------------------------------------------
- 콘솔 응용 프로그램 [프로젝트]에서 실행
==> [Program.cs]
using System.Data.SqlClient;
using System;
class Class1
{
static void Main()
{
// This is a simple example that demonstrates the usage of the
// BeginExecuteNonQuery functionality.
// The WAITFOR statement simply adds enough time to prove the
// asynchronous nature of the command.
string commandText =
"UPDATE Products SET ProductCount = ProductCount + 1 " +
"WAITFOR DELAY '0:0:5';" +
"UPDATE Products SET ProductCount = ProductCount - 1 ";
RunCommandAsynchronously(commandText, GetConnectionString());
Console.WriteLine("Press ENTER to continue.");
Console.ReadLine();
}
private static void RunCommandAsynchronously(
string commandText, string connectionString)
{
// Given command text and connection string, asynchronously execute
// the specified command against the connection. For this example,
// the code displays an indicator as it is working, verifying the
// asynchronous behavior.
using (SqlConnection connection =
new SqlConnection(connectionString))
{
try
{
int count = 0;
SqlCommand command = new SqlCommand(commandText, connection);
connection.Open();
IAsyncResult result = command.BeginExecuteNonQuery();
while (!result.IsCompleted) // 요청이 끝나기 전까지 무엇인가를 처리?
{
Console.WriteLine("Waiting ({0})", count++);
// Wait for 1/10 second, so the counter
// does not consume all available resources
// on the main thread.
System.Threading.Thread.Sleep(100);
}
Console.WriteLine("Command complete. Affected {0} rows.",
command.EndExecuteNonQuery(result));
}
catch (SqlException ex)
{
Console.WriteLine("Error ({0}): {1}", ex.Number, ex.Message);
}
catch (InvalidOperationException ex)
{
Console.WriteLine("Error: {0}", ex.Message);
}
catch (Exception ex)
{
// You might want to pass these errors
// back out to the caller.
Console.WriteLine("Error: {0}", ex.Message);
}
}
}
private static string GetConnectionString()
{
// To avoid storing the connection string in your code,
// you can retrieve it from a configuration file.
// If you have not included "Asynchronous Processing=true" in the
// connection string, the command is not able
// to execute asynchronously.
return "server=.;database=Market;uid=Market;pwd=6750440;asynchronous Processing=true;";
}
}
------------------------------------------------------------------------------------------------------
[실행결과]
'.NET프로그래밍 > ADO.NET' 카테고리의 다른 글
17. SqlTransaction 클래스 / TransactionScope 클래스 (0) | 2009.09.28 |
---|---|
16. 수정(Modify) / 삭제(Delete) (0) | 2009.09.28 |
15. 상세보기 (0) | 2009.09.28 |
14. 출력(CategoryList) (0) | 2009.09.28 |
13. 입력(Insert문을 넣어서 카테고리 추가하기) (0) | 2009.09.28 |