基于表单的应用程序中的线程 [英] Threads in Form Based Applicaitons

查看:49
本文介绍了基于表单的应用程序中的线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我正在尝试将字符串从一种形式传递到另一种形式,并希望在第二种形式处于运行状态时以第一种形式显示它.

我对线程概念非常陌生.请给我一些示例代码.



I am trying to pass a string from one form to another form and want to display it in first form while sencond form is in running state.

i am very munch new to threads concept . please suggest me with some sample code.

推荐答案

这与线程无关-纯粹是对象之间的数据传输问题.

为了在两个表单之间传输数据(假设Form1具有新数据,而Form2应该最终接收到它),您要么需要
1)要知道要在Form1中转移到的Form2实例

2)要让Form2订阅具有数据的Form1实例中的事件.

如果在Form1中执行此操作:
This has nothing to do with threads - it is purely a data transfer between objects problem.

In order to transfer data between two forms (assume Form1 has the new data, and Form2 should end up receiving it), you either need
1) To know the instance of Form2 you want to transfer to in Form1
or
2) To get Form2 to subscribe to an event in the instance of Form1 that will have the data.

If you do this in Form1:
Form2 f = new Form2();
f.Show();

然后您可以使用第一种方法.
1)将Form2实例保存在Form1的类级别变量中(这只是意味着将其移到任何方法代码之外,并在其前面放置"private".
2)在Form2中设置一个属性以接收数据并进行处理.
3)当您要将数据提供给Form2时,只需使用类级别变量设置属性值即可.

如果不这样做,则无论在何处创建Form2和Form2,都需要在Form2中设置事件并用信号通知事件,并设置Form1实例来处理该事件.
这稍微复杂一点(但是更好的解决方案)-如果需要,我可以为您提供详细信息.

Then you can use the first method.
1) Save the Form2 instance in a class level variable in Form1 (this just means moving it outside any method code and putting "private" in front of it.
2) Set up a Property in Form2 to receive the data, and handle it.
3) When you want to give the data to Form2, you just set the property value, using the class level variable.

If you don''t, then you will need to set up and signal an event in Form2, and set the Form1 instance to handle it, wherever you do create Form2 and Form2.
This is a little more complex (but a much better solution) - I can give you the details if you need them.


与线程无关.

这是关于表单协作的流行问题.最健壮的解决方案是在Form类中实现适当的接口,并传递接口引用而不是对Form的整个实例"的引用.请查看我过去的解决方案以获取更多详细信息:如何以两种形式在列表框之间复制所有项目 [ Control.Invoke()与Control.BeginInvoke() [ ^ ],
Treeview Scanner和MD5问题 [
It has nothing to do with threads.

This is the popular question about form collaboration. The most robust solution is implementation of an appropriate interface in form class and passing the interface reference instead of reference to a "whole instance" of a Form. Please see my past solution for more detail: How to copy all the items between listboxes in two forms[^].

As to using threading with Forms, this is a separate story. Please see my past solutions:
Control.Invoke() vs. Control.BeginInvoke()[^],
Problem with Treeview Scanner And MD5[^].

—SA


这篇关于基于表单的应用程序中的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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