C# “Local” variable loaded inside a task won't

2019-03-06 17:14发布

问题:

I'm running in circles with this one. I have some tasks on an HttpClient (.NET 4 with httpclient package from NuGet), in one of them i'm trying to assign a value to a variable that i declared OUTSIDE the task, at the beggining of the function, but when the execution gets to that point, the variable lost the assigned value and came back to the initial value, like it never changed. But I'm pretty sure it DID change at a moment, when the execution passed through the task.

I've made this screenshot to show it more easily:

What should I do to make my xmlString KEEP the value that was assigned to it inside the task, and use it OUTSIDE the task???

Thanks in advance for your help guys.

回答1:

Judging by your screenshot (it would be better if you provided the code in your question as well) you are never awaiting your task. Therefore, your last usage where you obtain the value of xmlString happens before your task has finished executing, and presumably before your .ContinueWith() has assigned the variable.

Ideally, your enclosing method should be async as well. Then you can simply await it. Otherwise, you can try calling the .ContinueWith(...).Wait() method first, though at that point your'e not leveraging async semantics at all.



回答2:

Why don't you use await? It makes the code a lot cleaner. Replace the client.GetAsync() line with the following:

HttpResponse resp = await client.GetAsync(par);

And then add the try-catch part of the Task. Then it should work as you originally intended it to!

EDIT:

Servy is half-right in the comments. Apart from the Microsoft.Net.HttpClient you will most probably need to manually add Microsoft.Bcl.Async too.