C#WinForms - 从UI线程控制工作线程 [英] C# WinForms - Control worker thread from UI thread

查看:124
本文介绍了C#WinForms - 从UI线程控制工作线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好!

我正在学习线程,我了解有关从工作线程更新UI线程的基础知识。

I am learning about Threading and I understand basics about updateing UI thread from worker thread.

但是怎么样反之亦然。

假设我们有一个带有无限while循环的工作线程(初始参数maxCounter = 10)。
$
inside While循环是一个计数器1,2,3 ... 10,1,2,3..10,1,2,3 ... 10 .....

它更新了UI控件(当前值为文本框的计数器)

Lets say we have a worker thread with infinite while loop (with initial parameter maxCounter = 10).
inside While loop is a counter which counts 1,2,3...10, 1,2,3..10, 1,2,3...10.....
and it updates UI control (current value of the counter to the textbox)

我想在表单上按一个按钮,然后将maxCounter值更改为例如。

我现在可以期待计算1,2,3 ...... 20,1,2,3 ... 20,....

I would like to press a button on my form, and change a maxCounter value to 20 for example.
I would now expect to count 1,2,3...20,1,2,3...20,....

我该怎么做?



我的maxCounter变量是否应被视为SharedResource,并且此变量的所有操作(读取和写入)应该是


使用锁同步?

How do I do this?

Should my maxCounter variable be treated as SharedResource and all operations (reads and writes) on this variable should be
synchronized using lock?

谢谢

推荐答案

对于 maxCounter ,你可能会使用
int ,根据文档,读取和写入都是原子的,即多个线程可以写入和读取此类数据。因此,您不需要
lock 或其他措施。

You will probably use int for maxCounter, and according to Documentation, reads and writes are atomic, i.e. multiple threads can write and read such data. Therefore, you do not need lock or other measures.

其他情况需要同步,例如'++'操作或
long type。

(参见"C#语言规范版本6",§5.5)。


这篇关于C#WinForms - 从UI线程控制工作线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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