Why does assigning a value to an unused variable make a difference in the functionality of this async code?

旧时模样 提交于 2019-12-22 09:54:10

问题


I've got this code:

private async Task SavePlatypusComplianceFileOnServer(string year, string month)
{
    string monthAsMM = ReportRunnerConstsAndUtils.GetMonthAsMM(month);
    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri(ReportRunnerConstsAndUtils.SERVER_BASE_ADDRESS);
    String uriToCall = String.Format("/api/PlatypusCompliance/{0}/{1}{2}", _unit, year, monthAsMM);
    HttpResponseMessage response = await client.PostAsync(uriToCall, null);
}

...that works fine.

On looking at it, though, I thought to myself, "Self, why are you assigning a value to "response" when you're not using it? Why not just call the method without that? After all, Visual Studio or Resharper greys out "response" to indicate to you that it's moot/redundant."

So I changed the code to this:

private async Task SavePlatypusComplianceFileOnServer(string year, string month)
{
    . . . // all but the last line of the code is exactly the same
    await client.PostAsync(uriToCall, null);
}

But with that change, all Dallas breaks loose - I get err msgs about tables not being able to be dropped because they don't exist, and the call to the method via PostAsync() does not succeed.

Why does it make a diffrence whether I assign a value to response when it is not used?

来源:https://stackoverflow.com/questions/34618315/why-does-assigning-a-value-to-an-unused-variable-make-a-difference-in-the-functi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!