我正在研究一个具有async
API的PCL(我是这个主题的新手)。从我在网上做的研究中,我对行为和设计影响感到困惑。假设应用程序使用一些入口点API来封装一些抽象底层来访问文件。假设这段代码正在运行客户端。嵌套和继承异步/任务
public interface IFileProcessor
{
Task ProcessFile(string filename);
}
public class MyFileProcessor : IFileProcessor
{
// Adapter can be SomeAdapter or SomeOtherAdapter
private IMyAdapter _adapter;
public Task ProcessFile(string filename)
{
File file = await _adapter.GetFileAsync(filename).ConfigureAwait(false);
// Some CPU bound operation
DoSomeWorkOnFile(file);
await _adapter.SaveAsync(file);
}
private void DoSomeWorkOnFile(File file)
{
// do some CPU heavy work here
}
}
internal interface IMyAdapter
{
Task<File> GetFileAsync(string filename);
Task SaveAsync(File file);
}
// Some adapter for a client that has an async API and is mainly I/O bound
internal class SomeAdapter : IMyAdapter
{
private SomeClient _client;
public async Task<File> GetFileAsync(string filename)
{
// Fetch from server or something
return await _client.SearchForFileAsync(filename).ConfigureAwait(false);
}
public async Task SaveAsync(File file)
{
// Push to server or something
await _client.SaveFileAsync(file).ConfigureAwait(false);
}
}
但说我有没有async
API及其操作阻塞另一个适配器:
// Some adapter for a client that has no async API and is mainly I/O bound
internal class SomeOtherAdapter : IMyAdapter
{
private SomeOtherClient _client;
// Don't declare as async since it can't await?
public Task<File> GetFileAsync(string filename)
{
// Read from disk or something
File file = _client.GetFile(filename);
return Task.FromResult(file);
}
public Task SaveAsync(File file)
{
// Write to disk or something
_client.Save(file);
}
}
- 是否
SomeOtherAdapter
有任何业务实现IMyAdapter
尽管行为不同? - 让IMyAdapter返回
Task
类型有什么好处吗?假定应用程序调用await MyFileProcessor.DoSomeWorkAsync(...)
,那么为什么要让适配器为async
? - 这些操作主要是I/O绑定的,而不是CPU绑定的 - 是否会影响我如何设计这些组件的决定?
我知道在一个简单的例子中很难捕捉到核心问题,所以我很抱歉,如果我给的例子太微不足道让我的问题变得清晰。
红利问题:如果MyFileProcessor
不需要做任何CPU绑定工作,那么使用async
根本就没有任何好处吗?
为什么downvote?这是一个真正的问题,我会愉快地重新格式化,并且我正在努力寻找全面的简洁资源。 – Softerware