开发者

Read a value being manipulated in different thread

开发者 https://www.devze.com 2022-12-27 03:56 出处:网络
I\'m trying to read a static property from a static class, which is being modified from a different thread.

I'm trying to read a static property from a static class, which is being modified from a different thread.

Basically I have this static class:

public static class Progress{
     public static int currentProgress{get; set;}
}

and this thread manipulating the currentProgress:

private void Job(){
    for(int i = 0; i<100; i++){
         Progress.currentProgress = i;
         Thread.Sleep(1000);
    }
}

While this is running, I have a HttpHandler trying to access this progress (every few seconds), like so:

public void ProcessRequest(HttpContext context) {
    context开发者_StackOverflow社区.Response.Write(Progress.currentProgress.toString());
    context.Response.End();
}

But the currentProgress is set to it's initialvalue here, while the workThread is working, and only when done, is the currentProgress updated.

I realize that this is probably a question of sync'ing the threads - but I can't quite seem to find the easiest way to accomplish this. Help please ;)


First step is to declare your static value as volatile.

0

精彩评论

暂无评论...
验证码 换一张
取 消