c# - 避免 Task 和 Task<T> 的重复方法

标签 c# .net task

我对 Task 有一些逻辑和 Task<T> . 有什么办法可以避免重复代码吗?

我当前的代码如下:

public async Task<SocialNetworkUserInfo> GetMe()
{
    return await WrapException(() => new SocialNetworkUserInfo());
}

public async Task AuthenticateAsync()
{
    await WrapException(() => _facebook.Authenticate());
}

public async Task<T> WrapException<T>(Func<Task<T>> task)
{
    try
    {
        return await task();
    }
    catch (FacebookNoInternetException ex)
    {
        throw new NoResponseException(ex.Message, ex, true);
    }
    catch (FacebookException ex)
    {
        throw new SocialNetworkException("Social network call failed", ex);
    }
}

public async Task WrapException(Func<Task> task)
{
    try
    {
        await task();
    }
    catch (FacebookNoInternetException ex)
    {
        throw new NoResponseException(ex.Message, ex, true);
    }
    catch (FacebookException ex)
    {
        throw new SocialNetworkException("Social network call failed", ex);
    }
}

最佳答案

您可以让 Task 重载调用另一个,并返回一个虚拟值。

public async Task WrapException(Func<Task> task)
{
    await WrapException<object>(async () => {
        await task();
        return null;
    });
}

或者,由于此处不需要 async 关键字:

public Task WrapException(Func<Task> task)
{
    return WrapException<object>(async () => {
        await task();
        return null;
    });
}

关于c# - 避免 Task 和 Task<T> 的重复方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23938411/

相关文章:

c++ - 将 textBox 传递给函数。 C++

c# - 从 sql server 数据库中检索图像

c# - 获取一个月中特定一周的日期

c# - 以编程方式删除 Sitecore 中的子布局

c# - 调用链中的异步等待分配

linux - Linux 中的任务调度程序行为

c# - 缓存可用于 WCF 和 ASP .NET 应用程序 (.NET 3.5)

c# - 人脸API "Access denied due to invalid subscription key..."

c# - 使用 FluentAssertions API 4.x 语法迁移 xunit 项目以使用 FluentAssertions v5.x 版本运行

c# - 任务取消最佳实践