C#中的AsyncCallback主要用于異步編程模型,它允許在異步操作完成時執行回調函數。以下是一些常見的AsyncCallback應用場景:
WebClient webClient = new WebClient();
webClient.DownloadStringCompleted += (sender, e) =>
{
string response = e.Result;
// 處理響應
};
webClient.DownloadStringAsync(new Uri("https://example.com"));
FileStream fileStream = new FileStream("example.txt", FileMode.Open, FileAccess.Read);
fileStream.BeginRead(new byte[1024], 0, 1024, ar =>
{
int bytesRead = ar.BytesRead;
// 處理讀取到的數據
}, null);
SqlConnection connection = new SqlConnection("your_connection_string");
SqlCommand command = new SqlCommand("SELECT * FROM your_table", connection);
connection.Open();
command.BeginExecuteReader(ar =>
{
SqlDataReader reader = (SqlDataReader)ar.AsyncState;
while (reader.Read())
{
// 處理讀取到的數據
}
}, command);
public class MyEventArgs : EventArgs
{
public string Message { get; set; }
}
public class MyEventPublisher
{
public event EventHandler<MyEventArgs> MyEvent;
public void RaiseEvent(string message)
{
MyEvent?.Invoke(this, new MyEventArgs { Message = message });
}
}
public class MyEventSubscriber
{
public void Subscribe(MyEventPublisher publisher)
{
publisher.MyEvent += (sender, e) =>
{
Console.WriteLine($"Message received: {e.Message}");
};
}
}
總之,AsyncCallback在C#中可以用于處理異步操作的結果,使得代碼更加簡潔和易于維護。