在C#中,異步線程的回調(diào)機(jī)制通常使用委托和事件來實(shí)現(xiàn)。當(dāng)一個(gè)異步操作完成時(shí),可以通過回調(diào)函數(shù)來處理其結(jié)果。
public delegate void AsyncCallback(string result);
public void DoAsyncWork(AsyncCallback callback)
{
// 模擬異步操作
Task.Run(() =>
{
Thread.Sleep(2000); // 模擬耗時(shí)操作
string result = "Async operation completed";
callback(result);
});
}
public void HandleCallback(string result)
{
Console.WriteLine($"Callback result: {result}");
}
// 調(diào)用異步操作并傳入回調(diào)函數(shù)
DoAsyncWork(HandleCallback);
public class AsyncWorker
{
public event EventHandler<string> WorkCompleted;
public void DoAsyncWork()
{
// 模擬異步操作
Task.Run(() =>
{
Thread.Sleep(2000); // 模擬耗時(shí)操作
string result = "Async operation completed";
WorkCompleted?.Invoke(this, result);
});
}
}
public class Program
{
public static void Main()
{
AsyncWorker worker = new AsyncWorker();
worker.WorkCompleted += HandleWorkCompleted;
// 調(diào)用異步操作
worker.DoAsyncWork();
}
public static void HandleWorkCompleted(object sender, string result)
{
Console.WriteLine($"Work completed: {result}");
}
}
以上代碼示例演示了如何在C#中實(shí)現(xiàn)異步線程的回調(diào)機(jī)制。通過使用委托或事件,可以在異步操作完成后觸發(fā)回調(diào)函數(shù)來處理結(jié)果。這種機(jī)制可以幫助我們實(shí)現(xiàn)異步編程中的回調(diào)功能,提高程序的靈活性和可維護(hù)性。