在我的自定义事件中
this.listBox1.Items.Add(e.Flag.ToString()) //走到这就不动了换成
MessageBox.show(e.Flag.ToString()) //这样就能弹出来换成
testBox 也不行,什么控件都不行一到这步程序就死掉
如果我在事件将 e放到集合里,然后再另一个线程中显示数据就没有问题,这怎么回事?
为什么没有多线程的时候一走到this.listBox1.Items.Add(e.Flag.ToString()) 这行就死掉?是主线程阻塞了?
this.listBox1.Items.Add(e.Flag.ToString()) //走到这就不动了换成
MessageBox.show(e.Flag.ToString()) //这样就能弹出来换成
testBox 也不行,什么控件都不行一到这步程序就死掉
如果我在事件将 e放到集合里,然后再另一个线程中显示数据就没有问题,这怎么回事?
为什么没有多线程的时候一走到this.listBox1.Items.Add(e.Flag.ToString()) 这行就死掉?是主线程阻塞了?
你定义的事件是什么东西,据我估计,是你调用完事件后阻塞了吧
也就是this.listBox1.Items.Add(e.Flag.ToString())执行完后就阻塞了(当然listBox1中已经加进去了,但是线程阻塞了,没法刷新而已)
而MessageBox.show(e.Flag.ToString())这句中,因为show是阻塞的,而且里面会有模态消息循环,所以东西能显示出来
其实程序根本不需要这些,我只是想看到测试结果才listBox.item.add的
如果在响应事件中我不做任何操作,把消息放到集合中,用另外一个线程来显示,就没有问题了我把代码拿来吧出错时的代码void eventWrapper_LocalOnClientLoginMessageToAppAgentEvent(ClientLoginMessage e, object sender)
{
this.listBox1.Items.Add("=====================");
this.listBox1.Items.Add(DateTime.Now.ToLongTimeString()+"\t"+e.Flag.ToString);
}
改用另一个线程显示就好了Thread threadclientmessage;
Queue<ClientLoginMessage> QclientMessage = new Queue<ClientLoginMessage>();this.threadclientmessage = new Thread(new ThreadStart(temp));
this.threadclientmessage.Start();
private void temp()
{
while (true)
{
if (this.QclientMessage.Count > 0)
{
ClientLoginMessage obj = this.QclientMessage.Dequeue();
this.listBox1.Items.Add("======================================");
this.listBox1.Items.Add(DateTime.Now.ToLongTimeString() + "\t" + obj.Flag.ToString());
}
Thread.Sleep(1);
}
}
能确定这个事件是在主线程调用的?如果这个事件是你写的类发布的,把你写的那个类贴出来
Windows服务做为Remoting的服务器,其它程序都是客户端,客户端之间的消息使用事件来传递的
代码虽然有点多,但还是贴上来吧远程接口/// <summary>
/// 网关向其它服务器发送的定位数据
/// </summary>
/// <param name="e"></param>
/// <param name="sender"></param>
public delegate void OnMessageForGatewayHander(HlGpsLibrary.GpsDataArgs e, object sender); /// <summary>
/// 各服务器向Windows服务发送的连接信息
/// </summary>
/// <param name="ClientName"></param>
public delegate void OnMessageToServerHander(string ClientName); /// <summary>
/// 应用代理服务器发送登录消息至数据库代理
/// </summary>
/// <param name="e"></param>
/// <param name="ennder"></param>
public delegate void OnClientLoginMessageToDBAgentHander(ClientLoginMessage e,object sender); /// <summary>
/// 数据库代理发送消息至应用代理
/// </summary>
/// <param name="e"></param>
/// <param name="ennder"></param>
public delegate void OnClientLoginMessageToAppAgentHander(ClientLoginMessage e, object sender); public interface IGpsRemote
{
event OnMessageForGatewayHander OnMessageForGatewayHanderEvent; event OnClientLoginMessageToDBAgentHander OnClientLoginMessageToDBAgentEvent; event OnClientLoginMessageToAppAgentHander OnClientLoginMessageToAppAgentEvent; void SendClientLoginMessageToAppAgent(ClientLoginMessage clientLoginMessage, object sender); void SendClientLoginMessageToDBAgent(ClientLoginMessage clientLoginMessage,object sender); void SendGatewayForCarMessage(HlGpsLibrary.GpsDataArgs gpsDataArgs, object sender); string ConnectServer(string clientName); }
工厂public class EventWrapper:MarshalByRefObject
{
public event OnMessageForGatewayHander LocalOnMessageForGatewayHanderEvent; public event OnClientLoginMessageToDBAgentHander LocalOnClientLoginMessageToDBAgentEvent; public event OnClientLoginMessageToAppAgentHander LocalOnClientLoginMessageToAppAgentEvent; public void SendGatewayForCarMessageing(HlGpsLibrary.GpsDataArgs gpsDataArgs, object sender)
{
//this.WriteLog("工厂: 调用了SendGatewayForCarMessageing方法");
this.LocalOnMessageForGatewayHanderEvent(gpsDataArgs, sender);
//this.WriteLog("工厂: 触发事件完成");
} public void SendClientLoginMessageToDBAgenting(ClientLoginMessage clientLoginMessage, object sender)
{
this.LocalOnClientLoginMessageToDBAgentEvent(clientLoginMessage, sender);
} public void SendClientLoginMessageToAppgenting(ClientLoginMessage clientLoginMessage, object sender)
{
this.LocalOnClientLoginMessageToAppAgentEvent(clientLoginMessage, sender);
} public override object InitializeLifetimeService()
{
return null;
} private void WriteLog(string message)
{
lock (this)
{
if (!System.IO.Directory.Exists(@"d:\RemoteServiceLog"))
{
System.IO.Directory.CreateDirectory(@"d:\RemoteServiceLog");
}
string filepath = @"d:\RemoteServiceLog\" + DateTime.Now.ToShortDateString() + ".txt";
System.IO.FileStream fs = new FileStream(filepath, FileMode.Append, FileAccess.Write, FileShare.Read);
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
sw.WriteLine(DateTime.Now.ToLongTimeString() + "\t" + message);
sw.Flush();
fs.Flush();
sw.Close();
fs.Close();
}
}
}
远程对象
public class GpsRemote:MarshalByRefObject,IGpsRemote
{
public event OnMessageForGatewayHander OnMessageForGatewayHanderEvent; public event OnMessageToServerHander OnMessageToServerHanderEvent; public event OnClientLoginMessageToDBAgentHander OnClientLoginMessageToDBAgentEvent; public event OnClientLoginMessageToAppAgentHander OnClientLoginMessageToAppAgentEvent; public void SendGatewayForCarMessage(HlGpsLibrary.GpsDataArgs gpsDataArgs, object sender)
{
//this.WriteLog("远程对象: 客户端调用了SendGatewayForCarMessage");
if (this.OnMessageForGatewayHanderEvent != null)
{
//this.WriteLog("远程对象: OnMessageForGatewayHanderEvent事件己被定阅");
OnMessageForGatewayHander tempEvent = null;
foreach(Delegate del in this.OnMessageForGatewayHanderEvent.GetInvocationList())
{
try
{
//this.WriteLog("远程对象: 准备触发OnMessageForGatewayHanderEvent事件");
tempEvent = (OnMessageForGatewayHander)del;
tempEvent(gpsDataArgs, sender);
//this.WriteLog("远程对象: 触发OnMessageForGatewayHanderEvent事件完成");
}
catch(Exception ex)
{
this.WriteLog("远程对象:\t" + ex.Message);
OnMessageForGatewayHanderEvent -= tempEvent;
//this.WriteLog("远程对象: OnMessageForGatewayHanderEvent事件被退定");
}
}
}
} public void SendClientLoginMessageToDBAgent(ClientLoginMessage clientLoginMessage, object sender)
{
if (this.OnClientLoginMessageToDBAgentEvent != null)
{
OnClientLoginMessageToDBAgentHander tempEvent = null;
foreach (Delegate del in this.OnClientLoginMessageToDBAgentEvent.GetInvocationList())
{
try
{
tempEvent = (OnClientLoginMessageToDBAgentHander)del;
tempEvent(clientLoginMessage, sender);
}
catch (Exception ex)
{
this.WriteLog("远程对象:\t" + ex.Message);
OnClientLoginMessageToDBAgentEvent -= tempEvent;
}
}
}
} public void SendClientLoginMessageToAppAgent(ClientLoginMessage clientLoginMessage, object sender)
{
if (this.OnClientLoginMessageToAppAgentEvent != null)
{
OnClientLoginMessageToAppAgentHander tempEvent = null; foreach (Delegate del in this.OnClientLoginMessageToAppAgentEvent.GetInvocationList())
{
try
{
tempEvent = (OnClientLoginMessageToAppAgentHander)del;
tempEvent(clientLoginMessage,sender);
}
catch (Exception ex)
{
this.WriteLog("远程对象:\t" + ex.Message);
this.OnClientLoginMessageToAppAgentEvent -= tempEvent;
}
}
}
}
public string ConnectServer(string ClientName)
{
if (this.OnMessageToServerHanderEvent != null)
{
try
{
this.OnMessageToServerHanderEvent(ClientName);
return "success";
}
catch
{
return "failure";
}
}
return "failure";
} public override object InitializeLifetimeService()
{
return null;
}
{
private GpsRemote GpsRemoteObj;
private Hashtable HtClientState = new Hashtable();
private ReaderWriterLock objReaderWriterLock = new ReaderWriterLock();
private Thread ThreadMoniton;
public Service1()
{
InitializeComponent();
} protected override void OnStart(string[] args)
{
string ServerIp = this.getServerIp();
this.WriteLog("启动服务\t服务器IP:"+ServerIp);
BinaryServerFormatterSinkProvider serverProvider = new BinaryServerFormatterSinkProvider();
BinaryClientFormatterSinkProvider clientProvider = new BinaryClientFormatterSinkProvider();
serverProvider.TypeFilterLevel = TypeFilterLevel.Full; IDictionary props = new Hashtable();
props["name"] = "YuHaiYang";
props["bindTo"] = ServerIp;
props["port"] = 8080;
props["rejectRemoteRequests"] = false; TcpChannel tcpChannel = new TcpChannel(props, clientProvider, serverProvider);
this.GpsRemoteObj = new GpsRemote();
ObjRef objRef = RemotingServices.Marshal(GpsRemoteObj, "GPSRemoteServer.soap");
this.GpsRemoteObj.OnMessageToServerHanderEvent += new DqhlGps.Common.OnMessageToServerHander(GpsRemoteObj_OnMessageToServerHanderEvent); this.ThreadMoniton = new Thread(new ThreadStart(this.ThreadMonitonClient));
this.ThreadMoniton.Start();
} void GpsRemoteObj_OnMessageToServerHanderEvent(string ClientName)
{
this.objReaderWriterLock.AcquireWriterLock(-1);
if (this.HtClientState.ContainsKey(ClientName))
{
this.HtClientState[ClientName] = DateTime.Now;
}
else
{
this.HtClientState.Add(ClientName, DateTime.Now);
this.WriteLog("客户端:" + ClientName + " 连接远程对象成功!");
}
this.objReaderWriterLock.ReleaseLock();
} private void ThreadMonitonClient()
{
while (true)
{
Thread.Sleep(60000);
this.objReaderWriterLock.AcquireWriterLock(-1);
int i = 0;
foreach (DictionaryEntry dictionaryEntry in this.HtClientState)
{
DateTime dt = (DateTime)dictionaryEntry.Value;
if (dt.AddMinutes(3) < DateTime.Now)
{
this.WriteLog(dictionaryEntry.Key.ToString() + "与远程服务器断开,上次连接时间" + dt.AddMinutes(-3).ToString());
}
else
{
this.WriteLog(dictionaryEntry.Key.ToString() + " 连接正常!");
}
i++;
}
this.objReaderWriterLock.ReleaseLock();
if (i == 0)
{
this.WriteLog("没有任何客户端连接服务器");
}
}
} protected override void OnStop()
{
this.WriteLog("停止服务");
try
{
if (this.ThreadMoniton != null)
{
this.ThreadMoniton.Abort();
}
}
catch { }
} private string getServerIp()
{
string hostName = System.Net.Dns.GetHostName();
System.Net.IPHostEntry entry = System.Net.Dns.GetHostEntry(hostName);
return entry.AddressList[0].ToString();
} private void WriteLog(string message)
{
lock (this)
{
if (!System.IO.Directory.Exists(@"d:\RemoteServiceLog"))
{
System.IO.Directory.CreateDirectory(@"d:\RemoteServiceLog");
}
string filepath = @"d:\RemoteServiceLog\" + DateTime.Now.ToShortDateString() + ".txt";
System.IO.FileStream fs = new FileStream(filepath, FileMode.Append, FileAccess.Write, FileShare.Read);
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
sw.WriteLine(DateTime.Now.ToLongTimeString() + "\t" + message);
sw.Flush();
fs.Flush();
sw.Close();
fs.Close();
}
}
}
/// <summary>
/// 注册远程通信服务器
/// </summary>
private void regRemoteService()
{
BinaryServerFormatterSinkProvider serverProvider = new BinaryServerFormatterSinkProvider();
BinaryClientFormatterSinkProvider clientProvider = new BinaryClientFormatterSinkProvider();
serverProvider.TypeFilterLevel = TypeFilterLevel.Full; IDictionary props = new Hashtable();
props["name"] = "YuHaiYang";
props["bindTo"] = this.objDBAgentApplication.RemotingIp;
props["port"] = this.objDBAgentApplication.LocalHosttPort;
props["rejectRemoteRequests"] = false; TcpChannel tcpChannel = new TcpChannel(props,clientProvider,serverProvider);
ChannelServices.RegisterChannel(tcpChannel, false); this.eventWrapper = new EventWrapper();
this.iGpsRemote = (IGpsRemote)Activator.GetObject(typeof(IGpsRemote), "tcp://" + this.objDBAgentApplication.RemotingIp + ":" + this.objDBAgentApplication.RemotingPort + "/GPSRemoteServer.soap"); this.ThreadConnectionRemotingServer = new Thread(new ThreadStart(this.connectionRemoteServer));
this.ThreadConnectionRemotingServer.Start(); } /// <summary>
/// 测试与远程服务器连接是否正常
/// </summary>
private void connectionRemoteServer()
{
while (true)
{
string connectionMessage="";
try
{
connectionMessage = this.iGpsRemote.ConnectServer("DBAgent");
if (connectionMessage != "success")
{
this.lstAppMessage.Items.Add(DateTime.Now.ToLongTimeString() + "\t远程服务监控线程:与Remote服务器连接失败!");
}
}
catch(Exception ex)
{
this.Writelog("连接远程服务器失败\t"+ex.Message);
this.objReaderWriterLock.AcquireWriterLock(-1);
this.lstAppMessage.Items.Add(DateTime.Now.ToLongTimeString()+"\t远程服务监控线程:与Remote服务器连接失败!");
this.objReaderWriterLock.ReleaseLock();
}
Thread.Sleep(60000);
}
} /// <summary>
/// 定阅远程服务器事件
/// </summary>
private void regRemoteEvent()
{
this.eventWrapper.LocalOnMessageForGatewayHanderEvent += new OnMessageForGatewayHander(eventWrapper_LocalOnMessageForGatewayHanderEvent);
this.iGpsRemote.OnMessageForGatewayHanderEvent += new OnMessageForGatewayHander(this.eventWrapper.SendGatewayForCarMessageing);
this.eventWrapper.LocalOnClientLoginMessageToDBAgentEvent += new OnClientLoginMessageToDBAgentHander(eventWrapper_LocalOnClientLoginMessageToDBAgentEvent);
this.iGpsRemote.OnClientLoginMessageToDBAgentEvent+=new OnClientLoginMessageToDBAgentHander(this.eventWrapper.SendClientLoginMessageToDBAgenting);
} void eventWrapper_LocalOnClientLoginMessageToDBAgentEvent(ClientLoginMessage e, object sender)
{
this.Writelog(e.ClientIP);
try
{
int i = this.objDataBaseOperate.clientLogin(e.LoginName,e.LoginPwd);
if (i == 1)
{
e.Flag = true;
}
else
{
e.Flag = false;
}
this.iGpsRemote.SendClientLoginMessageToAppAgent(e, this);
}
catch (Exception ex)
{
this.WriteErrorlog("错误:" + ex.Message + "\t" + ex.Source + "\t" + ex.StackTrace + "\t" + ex.TargetSite.Name);
}
} void eventWrapper_LocalOnMessageForGatewayHanderEvent(GpsDataArgs e, object sender)
{
try
{
this.objDataBaseOperate.insertGpsData(e);
this.lstAppMessage.Items.Add(e.GprsId + "\t" + e.CodeType.ToString() + "\t" + e.GpsTime.ToString());
}
catch (Exception ex)
{
this.WriteErrorlog("错误:" + ex.Message + "\t" + ex.Source + "\t" + ex.StackTrace + "\t" + ex.TargetSite.Name);
}
}
如e.Flag属性,或者e.Flag.ToString方法
但我觉得更有可能的不是(因为你用MessageBox.Show没问题)
this.listBox1.Items.Add(e.Flag.ToString())这句,而是这句后面的阻塞了
你试试在这句之后加上MessageBox.show(e.Flag.ToString())看看能不能Show出来
IGpsRemote iGpsRemote; Queue<ClientLoginMessage> QclientMessage = new Queue<ClientLoginMessage>();
public Form1()
{
InitializeComponent();
} private void Form1_Load(object sender, EventArgs e)
{
BinaryServerFormatterSinkProvider serverProvider = new BinaryServerFormatterSinkProvider();
BinaryClientFormatterSinkProvider clientProvider = new BinaryClientFormatterSinkProvider();
serverProvider.TypeFilterLevel = TypeFilterLevel.Full; IDictionary props = new Hashtable();
props["name"] = "YuHaiYang";
props["bindTo"] = "192.168.18.177";
props["port"] = 0;
props["rejectRemoteRequests"] = false; TcpChannel tcpChannel = new TcpChannel(props, clientProvider, serverProvider);
ChannelServices.RegisterChannel(tcpChannel, false); this.eventWrapper = new EventWrapper();
this.iGpsRemote = (IGpsRemote)Activator.GetObject(typeof(IGpsRemote), "tcp://192.168.18.177:8080/GPSRemoteServer.soap"); this.eventWrapper.LocalOnMessageForGatewayHanderEvent += new OnMessageForGatewayHander(eventWrapper_LocalOnMessageForGatewayHanderEvent);
this.iGpsRemote.OnMessageForGatewayHanderEvent+=new OnMessageForGatewayHander(eventWrapper.SendGatewayForCarMessageing); this.eventWrapper.LocalOnClientLoginMessageToAppAgentEvent += new OnClientLoginMessageToAppAgentHander(eventWrapper_LocalOnClientLoginMessageToAppAgentEvent);
this.iGpsRemote.OnClientLoginMessageToAppAgentEvent+=new OnClientLoginMessageToAppAgentHander(this.eventWrapper.SendClientLoginMessageToAppgenting); this.ThreadConnectionRemotingServer = new Thread(new ThreadStart(this.connectionRemoteServer));
this.ThreadConnectionRemotingServer.Start(); this.threadclientmessage = new Thread(new ThreadStart(temp));
this.threadclientmessage.Start(); }
private void temp()
{
while (true)
{
if (this.QclientMessage.Count > 0)
{
ClientLoginMessage obj = this.QclientMessage.Dequeue();
this.listBox1.Items.Add("======================================");
this.listBox1.Items.Add(DateTime.Now.ToLongTimeString() + "\t" + obj.Flag.ToString());
}
Thread.Sleep(1);
}
}
void eventWrapper_LocalOnClientLoginMessageToAppAgentEvent(ClientLoginMessage e, object sender)
{
this.QclientMessage.Enqueue(e);
//如果这里换成this.ListBox1.Items.add就出现以前的情况 }
private void connectionRemoteServer()
{
while (true)
{
string connectionMessage = "";
try
{
connectionMessage = this.iGpsRemote.ConnectServer("test");
if (connectionMessage != "success")
{
this.listBox1.Items.Add(DateTime.Now.ToLongTimeString() + "\t远程服务监控线程:与Remote服务器连接失败!");
}
}
catch (Exception ex)
{ this.listBox1.Items.Add(DateTime.Now.ToLongTimeString() + "\t远程服务监控线程:与Remote服务器连接失败!" + ex.Message);
}
Thread.Sleep(60000);
}
} private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
this.ThreadConnectionRemotingServer.Abort();
}
catch { }
try
{
this.threadclientmessage.Abort();
}
catch { }
} private void button2_Click(object sender, EventArgs e)
{
this.threadsendclientmessage = new Thread(new ThreadStart(this.sendmessage));
this.threadsendclientmessage.Start();
}
在this.listbox.items.add后面另代码不执行,我试过了,走到这一步程序就死掉
在16楼中
private void connectionRemoteServer()
{
while (true)
{
string connectionMessage = "";
try
{
connectionMessage = this.iGpsRemote.ConnectServer("test");//这儿打上断点1
if (connectionMessage != "success")
{
this.listBox1.Items.Add(DateTime.Now.ToLongTimeString() + "\t远程服务监控线程:与Remote服务器连接失败!");
}
}
catch (Exception ex)
{ this.listBox1.Items.Add(DateTime.Now.ToLongTimeString() + "\t远程服务监控线程:与Remote服务器连接失败!" + ex.Message);
}
Thread.Sleep(60000);//这儿打上断点2
}void eventWrapper_LocalOnClientLoginMessageToAppAgentEvent(ClientLoginMessage e, object sender)
{
this.QclientMessage.Enqueue(e);//这儿也打上断点3
//如果这里换成this.ListBox1.Items.add就出现以前的情况 }
据我的猜测,在断点一之后就到断点3,在断点3之后就到断点2
如果是这样的,说明你的事件根本不是在主线程执行的,而是在this.ThreadConnectionRemotingServer中执行的,你可以System.Threading.Thread.CurrentThread对比一下看看是不是