在C#中,设计AsyncCallback的逻辑需要遵循以下步骤:
public interface IAsyncCallback
{
void OnCompleted(string result);
void OnError(Exception ex);
}
public void PerformAsyncOperation(IAsyncCallback callback)
{
Task.Factory.StartNew(() =>
{
try
{
// 模拟异步操作,例如从数据库获取数据
Thread.Sleep(1000);
string result = "Async operation completed successfully.";
callback.OnCompleted(result);
}
catch (Exception ex)
{
callback.OnError(ex);
}
});
}
public void StartAsyncOperation()
{
IAsyncCallback callback = new AsyncCallbackImplementation();
PerformAsyncOperation(callback);
}
private class AsyncCallbackImplementation : IAsyncCallback
{
public void OnCompleted(string result)
{
Console.WriteLine("Result: " + result);
}
public void OnError(Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
在这个例子中,我们创建了一个名为AsyncCallbackImplementation的类,它实现了IAsyncCallback接口。在StartAsyncOperation方法中,我们创建了AsyncCallbackImplementation的实例,并将其传递给PerformAsyncOperation方法。当异步操作完成或出错时,回调方法将被调用,从而实现了回调逻辑。