关于在窗体中使用多线程调用控件的方式

小弟之前在窗体的多线程内调用控件,使用:

System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;

这条语句,网上好像都不建议这么使用,唉,本人用这种方式调试程序也报错,实在没辙,就采用了另外一种网上认为稍微优化点儿的方式,如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Threading;
namespace WindowsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Thread threadGet1, threadGet2;

            threadGet1 = new Thread(new ThreadStart(doGetFromXml1));

            threadGet2 = new Thread(new ThreadStart(doGetFromXml2));

            threadGet1.St
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Java,如果需要在一个线程窗体控件赋值,需要注意以下几点: 1. 窗体控件只能在创建它的线程进行操作,如果在其他线程直接修改窗体控件,程序会抛出异常。 2. 如果需要在其他线程更新窗体控件的值,可以使用Java Swing提供的方法SwingUtilities.invokeLater()。该方法可以将更新控件的操作放到事件队列,以便在Swing的事件调度线程执行,从而避免多线程冲突。 下面是一个简单的示例代码,演示如何在Java使用线程更新窗体控件的值: ``` import javax.swing.*; public class MainFrame extends JFrame { private JLabel label; public MainFrame() { label = new JLabel("Hello, world!"); add(label); setSize(200, 200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public void updateLabelText(final String text) { SwingUtilities.invokeLater(new Runnable() { public void run() { label.setText(text); } }); } } public class Main { public static void main(String[] args) { final MainFrame frame = new MainFrame(); new Thread(new Runnable() { public void run() { while (true) { frame.updateLabelText("Time: " + System.currentTimeMillis()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); } } ``` 在这个示例代码,我们创建了一个包含一个标签控件窗体MainFram,然后创建了一个线程,每隔一秒钟更新标签的文本。在updateLabelText方法,我们使用SwingUtilities.invokeLater方法将更新控件的操作放到事件队列,从而避免多线程冲突。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值