在第二个线程的主线程中定义的访问变量?(Access variables defined in main thread in second thread?)

编程入门 行业动态 更新时间:2024-10-25 21:18:36
第二个线程的主线程中定义的访问变量?(Access variables defined in main thread in second thread?)

在我的C#控制台应用程序中,我启动一个新任务并调用一个函数,该函数要求我能够访问在主线程中定义的变量,例如:

class Example { static int ExampleVarForQuestion = 1; int Main() { new Task(WhereProblemOccures.ExampleFunction).Start(); } } class WhereProblemOccures { static int ExampleFunction() { if(Example.ExampleVarForQuestion == 1) return 1; else return 0; } }

问题是在ExampleVarForQuestion()无法达到上述变量值ExampleVarForQuestion 。 我对C#很陌生,所以如果这个问题没有措辞,那就非常抱歉了。

In my C# console application, I start a new task and call a function that requires me to be able to access variables that were defined in the main thread, for example:

class Example { static int ExampleVarForQuestion = 1; int Main() { new Task(WhereProblemOccures.ExampleFunction).Start(); } } class WhereProblemOccures { static int ExampleFunction() { if(Example.ExampleVarForQuestion == 1) return 1; else return 0; } }

The problem is that the above variable value ExampleVarForQuestion is not able to be reached in ExampleVarForQuestion(). I'm quite new to C#, so if this question wasn't worded very good sorry about that.

最满意答案

为了达到它,它必须是公共的,因为你的方法是在另一个类中定义的。

请注意,如果该成员将由另一个线程编写,您应该添加某种形式的同步以保证线程安全。

For it to be reached it must be public as your method is defined in another class.

Note that if the member is going to be written by another thread you should add some form of synchronization to guarantee thread safety.

更多推荐

本文发布于:2023-07-29 15:47:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1317577.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:第二个   线程   主线   变量   定义

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!