C#“本地”任务内部加载的变量在任务外部调用时不会保留其值 [英] C# "Local" variable loaded inside a task won't keep its value when called outside the task

查看:109
本文介绍了C#“本地”任务内部加载的变量在任务外部调用时不会保留其值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与此圈子里奔跑。我在HttpClient(带有来自NuGet的带有httpclient程序包的.NET 4)上有一些任务,在其中之一中,我试图在函数开始时将一个值赋给我声明为超出任务的变量,但是当执行到这一点,变量就失去了分配的值,并回到了初始值,就像它从未改变过一样。但是我很确定执行任务通过任务时,它会立即发生DID更改。

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:

我应该怎么做才能使xmlString保持在任务中分配给它的值,并在任务外使用它?

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.

推荐答案

从您的屏幕截图来看(如果您还提供问题中的代码会更好),您永远不会等待任务。因此,最后一次获得 xmlString 值的用法是 之前,您的任务已完成执行,并且大概在之前.ContinueWith()分配了变量。

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.

理想情况下,您的封装方法也应该是异步的。然后,您可以简单地等待它。否则,您可以尝试首先调用 .ContinueWith(...)。Wait()方法,尽管那时候您根本就没有利用异步语义。

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.

这篇关于C#“本地”任务内部加载的变量在任务外部调用时不会保留其值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆