那么,为什么线程不喜欢设置或获取变量? [英] So, why do threads not like to set or get variables?

查看:52
本文介绍了那么,为什么线程不喜欢设置或获取变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

令人沮丧的是,这个论坛似乎并不理解问题。所以,由于他们删除了我的问题,我想; 为什么不用简单的细节重新发布它。



我在这里有一个很好的空白:



  public   void  ReloadChunks()
{
// - 一个小提示:看一下如何在线程中创建它。
VariableNotInTheThread = 1 ;
}





所以,我可以在没有线程的情况下做到这一点但是它滞后于我的UI。因此,我想让它成为线程。但是你不能在线程中设置非静态变量。我的问题是我该怎么做?

解决方案

当然你可以在一个线程中设置一个静态变量,但想想它是否有意义。但是如果一个变量是静态的,那么它可以被其他一些线程访问。如果不是,则没有问题(存在潜在问题),但是,没有必要使对象静态。因此,如果它是静态的,你可以这样做:

  static   internal   int  VariableNotInTheThread =  0 ;  //  或其他内容 
static 内部 对象 LockObject = new 对象();
// ...

public void ReloadChunks()
{
lock (LockObject)
VariableNotInTheThread = 1 ;
}





因此,如果你跨线程使用任何东西,你应该同步它;在这种情况下,与锁。根据经验,静态物体是邪恶的。



然而,这是一种不好的技术应该很少使用。对于一种好的技术,请参阅我的答案,其中我介绍了非常有用的线程包装器,特别是允许您以封装方式共享对象,并避免使用静态对象:

如何将ref参数传递给线程 [ ^ ],

更改线程(生产者)启动后的参数 [ ^ ](这个带锁)。



-SA

It''s frustrating how this forum does not seem to understand questions. So, as a result of them deleting my question I thought; "Why not just repost it with simple details".

I have a nice void here:

public void ReloadChunks()
{
 // -- A small hint: Look how this is not created in the thread.
 VariableNotInTheThread = 1;
}



So, I can do this without a thread but it lags my UI. So, therefor I would like to make it threaded. But you can NOT set non static variables in threads. My question is how would I do that?

解决方案

Of course you can set a static variable in a thread, but think if it makes any sense or not. But if a variable is static, it can be accessed by some other thread. If it is not, there is no a problem (there is a potential problem), but then, there is no need to make an object static. So, if it is static, you can do this:

static internal int VariableNotInTheThread = 0; // or something
static internal object LockObject = new object();
// ...

public void ReloadChunks()
{
    lock (LockObject)
       VariableNotInTheThread = 1;
}



So, if you use anything across threads, you should synchronize it; in this case, with the lock. Static objects are evil, as a rule of thumb.

However, this is a bad technique which should rarely be used. For one of good techniques, please see my answers where I introduced the very useful thread wrapper which, in particular, allows you to share objects in an encapsulated way, and avoid static objects:
How to pass ref parameter to the thread[^],
change paramters of thread (producer) after it started[^] (this one with lock).

—SA


这篇关于那么,为什么线程不喜欢设置或获取变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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