【问题标题】:Implementing asynchronously methods synchronously [duplicate]同步实现异步方法[重复]
【发布时间】:2015-03-29 20:08:45
【问题描述】:

我有一个抽象类FilesManager 管理一些文件。

这些方法被标记为Task<>,因为我可能正在通过http request将文件保存/读取到云服务器,所以我想将它们标记为asynchronous

但是,现在,我将文件保存在本地磁盘上,synchronusly

是否可以返回空Task 以修复错误?

例如:

return Task.Factory.StartNew(() => { return; });

LocalDiskFilesManager 的以下实现抛出异常,因为每个方法都应该返回一个 Task<> 对象。

public abstract class FilesManager
{
    public abstract Task SaveFileAsync(XDocument xDocument);
    public abstract Task<XDocument> GetFileAsync(Guid file_Id);
}

// Synchronously
public class LocalDiskFilesManager : FilesManager
{
    public override Task SaveFileAsync(XDocument xDocument)
    {
        string path = GetFilePath();
        xDocument.Save(path);

        // is ok to return an empty task? does it affects the performance / threads?
        // return Task.Factory.StartNew(() => { return; });
    }

    public override Task<XDocument> GetFileAsync(Guid file_Id)
    {
        string path = GetFilePath(file_Id);
        XDocument xDocument = XDocument.Load(path);

        return xDocument;

        // is ok to return an empty task? does it affects the performance / threads?
        // return Task<XDocument>.Factory.StartNew(() => { return xDocument; });
    }
}

【问题讨论】:

  • 另见this answer
  • 我认为该答案解释了如何同步运行异步任务,但我需要知道如何“伪造”同步任务以使其看起来异步 :)

标签: c# asp.net asynchronous async-await


【解决方案1】:

现在最好使用Task.FromResult

创建一个Task&lt;TResult&gt;,它以指定的结果成功完成。

例如

public override Task<XDocument> GetFileAsync(Guid file_Id)
{
    string path = GetFilePath(file_Id);
    XDocument xDocument = XDocument.Load(path);

    return Task.FromResult(xDocument);
}

这避免了实际安排单独的任务,因此应该解决您的线程问题。

对于非泛型 Task,我通常会这样做:

private static Task _alreadyDone = Task.FromResult(false);

public override Task SaveFileAsync(XDocument xDocument)
{
    string path = GetFilePath();
    xDocument.Save(path);

    return _alreadyDone;
}

【讨论】:

  • 太棒了!谢谢你。您将_alreadyDone 标记为静态有什么具体原因吗?
  • @RaraituL - 这是一个过早的优化 - 你可以只使用 return Task.FromResult(false); 方法,但由于该任务没有什么有趣的,我们不妨创建一个,一次,然后总是返回它。保存分配。
猜你喜欢
  • 1970-01-01
  • 2016-01-01
  • 2018-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多