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#中可以用于处理异步操作的结果,使得代码更加简洁和易于维护。