在后台工作线程中使用C#全局变量是否安全? [英] Is it safe to use C# global variables in a background worker thread

查看:221
本文介绍了在后台工作线程中使用C#全局变量是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨 我正在开发一个简单的桌面应用程序,它需要处理一些操作,例如加载可能会阻塞主线程的网页,因此我将代码移至了后台工作程序.

Hi I am working on a simple desktop application, it needs to handle some operations like loading a webpage which may block the main thread, so i moved the code to a background worker.

我的问题是有一个名为UCSProject的重载类,其中包含许多字符串和List字段,我需要将此类的实例传递给后台工作者,因为该类有点重,我想减少直接使用全局变量而不是将其作为参数传递给后台工作程序的重复实例数.

My problem is there is a heavy class named UCSProject, which contains many string and List fields, i need to pass an instance of this class to the background worker, since the class is a bit heavy, i would like to reduce the number of duplicate instances by using the global variable directly, instead of passing it as an argument to the background worker.

简而言之,我只想知道从C#中的后台工作线程访问全局变量是否安全

To make it short, I just want to know is it safe to access global variables from a background worker thread in C#

推荐答案

除非您的两个线程(后台和正常)都没有修改该对象,否则它是安全的.

It is safe unless until both your threads(background & normal) not modifying the object.

如果您希望彼此修改对象,请使用锁定

If you want your object to be modified by each other, use Lock

这篇关于在后台工作线程中使用C#全局变量是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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