c# - 线程跨类添加项目列表框

标签 c# multithreading listbox

我在线程与类结合方面遇到问题。 对于我的问题,我编写了一个简单的代码来解释我的问题。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace RemoteMonitorServer
{
    public partial class RemoteMonitor : Form
    {
        Thread cThread;
        Server cServer;

        public RemoteMonitor()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            WriteLog("Programm started!");

            cServer = new Server();
            cThread = new Thread(new ThreadStart(cServer.StartServer));
            cThread.IsBackground = true;
            cThread.Start();
        }

        public void WriteLog(string sText)
        {
            MessageBox.Show(sText);
            listBox1.Items.Add(sText);
        }
    }
}

该类具有以下代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RemoteMonitorServer
{
    class Server
    {
        public void StartServer()
        {
            RemoteMonitor cTest = new RemoteMonitor();

            cTest.WriteLog("Thread started!");
        }
    }
}

现在,当我启动此代码时,列表框确实会显示“程序已启动!”但不是“线程开始!”。 虽然我收到两条 MessageBox 消息,但我相信该方法正在被调用。 Visual Studio 2010 中没有错误,有人可以告诉我我在这里做错了什么吗?

最佳答案

public delegate void RunAtFormThreadCallBack(Control control, RunningAtFormThread method);
private void RunAtFormThread(Control control, RunningAtFormThread method)
{

        if (control.InvokeRequired)
        {
            var callback = new RunAtFormThreadCallBack(RunAtFormThread);
            control.Invoke(callback, new object[] { control, method });
        }
        else
            method.Invoke();
}

用法:

RunAtFormThread(listBox1, delegate
                            {
   // executing at control thread...
   listBox1.Items.Add(sText); 
   MessageBox.Show(sText);
});

关于c# - 线程跨类添加项目列表框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12467181/

相关文章:

c# - XNA:我怎样才能只绘制我的 Sprite 的 "pizza slice"?

javascript web workers多线程字符串搜索比单线程慢?

java - 如何使用wait()和notifyAll()来一一运行线程?

windows-phone-7 - WP7 列表框滚动不起作用

wpf - 如何通过绑定(bind)清除列表框的所选项目

wpf - ItemTemplate:ListBox 与 ItemsControl

C# 编译器错误地优化了代码

c# - 在 View 的引擎 Razor 中将参数作为模型传递

c# - 以编程方式创建 GroupBox 并在其中添加标签

.net - 检查AutoResetEvent状态