简体   繁体   English

从主线程获取后台任务的数据

[英]Fetching data of a background task from main thread

Here I have got a global variable which stores the index of a for loop. 在这里,我有一个全局变量,用于存储for循环的索引。 It's a long running process so the for each is done inside a Task . 这是一个长期运行的过程,因此每个过程都在Task完成。 Inside that Task the index value is stored into a variable. 在该Task内部,索引值存储在变量中。 While the background process runs I have another method which gets the value from the global variable. 在后台进程运行时,我有另一种方法可以从全局变量获取值。 But it returns incorrect. 但是它返回不正确。

int myCount = -1;
Task BackgroundTask;
List<int> Count = new List<int>();

protected void Run_Click(object sender, EventArgs e)
{
    BackgroundTask = new Task(() =>
        {
            for (int i = 0; i < 1000000; i++)
            {
                myCount = myCount + 1;
                Thread.Sleep(1000);
            }
        });
    BackgroundTask.Start();
}

protected void Check_Click(object sender, EventArgs e)
{
    Count.Add(myCount);            
}

Here while accessing the value of the variable myCount always returns -1 when done with Check_Click method. 在这里,当使用Check_Click方法完成访问变量myCount的值时, myCount始终返回-1。 But the thread is still running. 但是线程仍在运行。 Why is it so and how can I get the count value without making the variable static? 为什么会这样,如何在不使变量静态的情况下获得计数值?

It seems to be related to compiler optimizations. 它似乎与编译器优化有关。 try marking your index variable definition with volatile keyword which informs the compiler about the fact that multiple threads will access the variable. 尝试用volatile关键字标记索引变量定义,该变量将告知编译器多个线程将访问该变量的事实。

volatile int myCount = -1;
Task BackgroundTask;
//rest of the code

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

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