- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Text;
- using System.Windows.Forms;
- using System.Threading;
- namespace 线程访问窗体的控件
- {
- public partial class Form1 : Form
- {
- private Service service;
- public Form1()
- {
- InitializeComponent();
- }
- private void button1_Click(object sender, EventArgs e)
- {
- service = new Service(listBox1);
- progressBar1.Value = 20;
- Thread s=new Thread(new ThreadStart(send));
- s.Start();
- }
- private void send()
- {
- //listBox1.Items.Add("1111");
- service.AddListBoxItem("1111");
- progressBar1.Value = 50;
- }
- }
- class Service
- {
- private ListBox listbox;
- //用于操作另一个线程的控件
- private delegate void AddListBoxItemCallback(string str);
- private AddListBoxItemCallback addListBoxItemCallback;
- public Service(ListBox listbox)
- {
- this.listbox = listbox;
- addListBoxItemCallback = new AddListBoxItemCallback(AddListBoxItem);
- }
- public void AddListBoxItem(string str)
- {
- //比较调用AddListBoxItem方法的线程和创建listBox的线程是否同一个线程
- //如果不是,则listBox的InvokeRequired为true
- if (listbox.InvokeRequired == true)
- {
- //用委托执行AddListBoxItem方法,
- //listbox.Invoke会导致listbox.InvokeRequired返回false
- //所以委托调用该方法时执行的是else中的内容
- listbox.Invoke(addListBoxItemCallback, str);
- }
- else
- {
- //包含listbox的窗体关闭时会导致listbox.IsDisposed返回true
- if (listbox.IsDisposed == false)
- {
- listbox.Items.Add(str);
- listbox.SelectedIndex = listbox.Items.Count - 1;
- listbox.ClearSelected();
- }
- }
- }
- }
- }
线程访问窗体的控件方法
最新推荐文章于 2022-06-26 10:41:48 发布