简体   繁体   English

等待异步任务后重置变量

[英]Variable reset after await async Task

I've got a windows forms app where the code for the form contains this: 我有一个Windows窗体应用程序,其中该窗体的代码包含以下内容:

public partial class Form1 : Form
{
    bool testBool;

    public Form1()
    {
        InitializeComponent();
    }

    private async void Form1_Load(object sender, EventArgs e)
    {
        try
        {
            await new Form1().Run();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error: " + ex.Message);
        }

        Console.WriteLine(testBool);
    }

    private async Task Run()
    {
        Console.WriteLine(testBool);
        testBool = true;
        Console.WriteLine(testBool);
    }
}

What I've noticed is that the result I get in the Console is 我注意到的是,我在控制台中得到的结果是

false
true
false

Where I would expect it to be 我希望它在哪里

false
true
true

What is happening to testBool during this process? 在此过程中, testBool发生了什么? Is there a way I can preserve the value of this variable after Run() is complete? Run()完成后,是否有办法保留此变量的值?

testBool is a instance field, every Form1 will have a different ones. testBool是一个实例字段,每个Form1都会有一个不同的字段。 If you want them to share the same testBool field, mark it as static : 如果您希望他们共享相同的testBool字段,请将其标记为static

public partial class Form1 : Form
{
    static bool testBool;
}

static (C# Reference) 静态(C#参考)

Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object . 使用static修饰符声明一个静态成员, 成员属于类型本身而不是特定对象 The static modifier can be used with classes, fields, methods, properties, operators, events, and constructors, but it cannot be used with indexers, destructors, or types other than classes. 静态修饰符可以与类,字段,方法,属性,运算符,事件和构造函数一起使用,但不能与除类之外的索引器,析构函数或类型一起使用。 For more information, see Static Classes and Static Class Members (C# Programming Guide). 有关更多信息,请参见静态类和静态类成员(C#编程指南)。

As mentioned in the comments to your question, you are accessing two different instances of your Form1 class. 如对问题的评论中所述,您正在访问Form1类的两个不同实例。

You are instantiating a new Form1 and calling the Run method of that new object, which will print out false then true , then when it returns from that, it writes the original Form1 instances value of testBool which is still false . 您将实例化一个新的Form1并调用该新对象的Run方法,该方法将打印出false然后为true ,然后从该对象返回时,它将写入testBool的原始Form1实例值,该值仍为false

You may want to define your class as static , or at least provide a public static field, or private static with a public static field accessor property or function. 您可能希望将您的类定义为static ,或者至少提供一个公共静态字段,或为私有静态提供一个公共静态字段访问器属性或函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM