使用的最佳方法是什么?

时间:2020-06-19 13:37:32

标签: c# asp.net-core using

使用的最佳方法是什么?

代码1:

public async Task<IActionResult> EditEmployeePicture(string userId)
{
    using IClubRep current = new ClubRep(_db);
    var data = await current.CurrentUserData(user.Id);
}

code2:

public async Task<IActionResult> EditEmployeePicture(string userId)
{
    using (IClubRep current = new ClubRep(_db))
    {
        var data = await current.CurrentUserData(user.Id);
    }
}

code3:

private IClubRep Club { get; set; }
.
.
.
public async Task<IActionResult> EditEmployeePicture(string userId)
{
    Club = new ClubRep(_db);
    var data = await Club.CurrentUserData(user.Id);
}

您认为最佳的使用方式是什么? 对系统的压力最小。

1 个答案:

答案 0 :(得分:2)

使用code1:由于编译器生成的try / catch / finally块包含了所有代码,因此您的可使用期限将一直持续到方法结束。使用code2:它仅能生存到using块的末尾,因为编译器会为该部分生成单独的try / catch / finally。

在您的示例中,它们是完全相同的,但是如果在此之后有大量代码:using IClubRep current = new ClubRep(_db);,则一次性对象的寿命会稍长一些。