我有一個線程與類組合的問題。 對於我的問題,我做了一個簡單的代碼來解釋我的問題。線程交叉類添加項目列表框
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);
}
}
}
類具有下面的代碼:「PROGRAMM開始」
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中沒有錯誤,有人可以告訴我我在做什麼錯誤嗎?
這是因爲你從運行'StartServer'的線程對'listBox1.Items.Add'有一個無效的跨線程調用。不知道爲什麼它沒有拋出異常 - 你是否禁用了無效的跨線程調用檢查? –
不,我沒有設置checkforillegalcrossthreadcalls爲false。 – SmartGuyz