在一个类中通过事件委托的方法将该类中得到的信息委托出去执行,但委托出去的事件在调用中不能使用窗体中的控件信息,什么原因呀!!!!

清风树下 2007-11-26 04:02:51
我做一个TCP客户端连接的类,将该类中接收到的一个数据通过委托事件的方法委托出去由用户定义,可是在调用时定义委托的事件可以,但不能使用窗体中的控件等信息一使用就报错。该如何做呀!!!

这是一些基本定义信息:

#region 注册信息
/// <summary>
/// Sockets连接基本信息格式
/// </summary>
public class TchSocketsInfo
{
#region 连接信息

/// <summary>
/// SocketID
/// </summary>
private string ClientID = System.Guid.NewGuid().ToString(); //Socket连接ID

/// <summary>
/// 获取/设置Socket连接ID
/// </summary>
public string SetClientID
{
get { return this.ClientID; }
set { this.ClientID = value; }
}

/// <summary>
/// Socket名称
/// </summary>
private string ClientName = System.Guid.NewGuid().ToString(); // Socket名称

/// <summary>
/// 获取/设置Socket连接名称
/// </summary>
public string SetClientName
{
get { return this.ClientName; }
set { this.ClientName = value; }
}

/// <summary>
/// Socket连接类型(TCP\UDP\Client\Port)
/// </summary>
private string ClientType = "TCP";

/// <summary>
/// 获取/设置Socket连接类型(TCP\UDP\Client\Port)
/// </summary>
public string SetClientType
{
get { return this.ClientType; }
set { this.ClientType = value; }
}

/// <summary>
/// 连接Socket
/// </summary>
private Socket ClientSocket = null; //连接Socket

/// <summary>
/// 获取/设置连接Socket
/// </summary>
public Socket SetClientSocket
{
get { return this.ClientSocket; }
set { this.ClientSocket = value; }
}

/// <summary>
/// 指示连接是否成功
/// </summary>
private bool Bool_True = false;

/// <summary>
/// 获取/设置连接是否成功,为True是表示连接成功
/// </summary>
public bool SetBool_True
{
get { return this.Bool_True; }
set { this.Bool_True = value; }
}

/// <summary>
/// 记录该连接的连接时间
/// </summary>
private DateTime ClientConnect = DateTime.Now;

/// <summary>
/// 获取/设置连接的时间
/// </summary>
public DateTime SetClientConnect
{
get { return this.ClientConnect; }
set { this.ClientConnect = value; }
}

/// <summary>
/// 记录最后一次接收数据的时间
/// </summary>
private DateTime ClientDTConnect = DateTime.Now;

/// <summary>
/// 获取/设置最后一次接收数据的时间
/// </summary>
public DateTime SetClientDTConnect
{
get { return this.ClientDTConnect; }
set { this.ClientDTConnect = value; }
}

/// <summary>
/// 连接失效时间 单位:分钟
/// </summary>
private int Int_FailureTime = 1;

/// <summary>
/// 获取/设置连接失效时间(1) 单位:分钟
/// </summary>
public int SetFailureTime
{
get { return this.Int_FailureTime; }
set { this.Int_FailureTime = value; }
}


#endregion

#region 异步接收数据
/// <summary>
/// 异步接收数据存放的变量
/// </summary>
private byte[] ClientrecByte = null;

/// <summary>
/// 获取/设置异步接收数据存放的变量
/// </summary>
public byte[] SetClientrecByte
{
get { return this.ClientrecByte; }
set { this.ClientrecByte = value; }
}

/// <summary>
/// 异步接收数据时一次接收数据的大小
/// </summary>
private int Int_ByteSize = 1024;

/// <summary>
/// 获取/设置异步接收数据时一次接收数据的大小(1024) 单位:字节
/// </summary>
public int SetByteSize
{
get { return this.Int_ByteSize; }
set
{
this.Int_ByteSize = value;
this.ClientrecByte = new byte[value];
}
}

#endregion

#region 初次握手发送信息
/// <summary>
/// 是否发送握手信息
/// </summary>
private bool Bool_Shake = false;

/// <summary>
/// 获取/设置是否发送握手信息
/// </summary>
public bool SetBool_Shake
{
get { return this.Bool_Shake; }
set { this.Bool_Shake = value; }
}

/// <summary>
/// 是否发送握手信息还是ID信息,为True是表示握手信息
/// </summary>
private bool Bool_ShakeCode = true;

/// <summary>
/// 获取/设置是否发送握手信息还是ID信息,为True是表示握手信息
/// </summary>
public bool SetBool_ShakeCode
{
get { return this.Bool_ShakeCode; }
set { this.Bool_ShakeCode = value; }
}

/// <summary>
/// 初次握手发送信息
/// </summary>
private string Str_Txt = "Technic";

/// <summary>
/// 获取/设置初次握手发送信息
/// </summary>
public string SetStrTxt
{
get { return this.Str_Txt; }
set { this.Str_Txt = value; }
}

/// <summary>
/// 发送握手信息延迟时间 单位:毫秒
/// </summary>
private int Int_Interval = 0;

/// <summary>
/// 获取/设置发送握手信息延迟时间 单位:毫秒
/// </summary>
public int SetIntInterval
{
get { return this.Int_Interval; }
set { this.Int_Interval = value; }
}
#endregion

#region 心跳信息
/// <summary>
/// 心跳标识 是否启动心跳
/// </summary>
private bool Bool_HeartBit = false;

/// <summary>
/// 获取/设置心跳标识 是否启动心跳
/// </summary>
public bool SetBoolHeartBit
{
get { return this.Bool_HeartBit; }
set { this.Bool_HeartBit = value; }
}

/// <summary>
/// 心跳字符
/// </summary>
private string Str_HeartStr = "@";

/// <summary>
/// 获取/设置心跳字符
/// </summary>
public string SetStrHeartStr
{
get { return this.Str_HeartStr; }
set { this.Str_HeartStr = value; }
}

/// <summary>
/// 心跳间隔时间 单位:秒
/// </summary>
private int Int_HeartTime = 60;

/// <summary>
/// 获取/设置心跳间隔时间 单位:秒
/// </summary>
public int SetIntHeartTime
{
get { return this.Int_HeartTime; }
set { this.Int_HeartTime = value; }
}

/// <summary>
/// 接收心跳字符发送心跳,为空时表示心跳跳动正常
/// </summary>
private string Str_HeartShowStr = "";

/// <summary>
/// 获取/设置接收心跳字符,为空时表示心跳跳动正常
/// </summary>
public string SetSStrHeartShowStr
{
get { return this.Str_HeartShowStr; }
set { this.Str_HeartShowStr = value; }
}
#endregion

/// <summary>
/// 实时监控连接的状态/心跳启动
/// </summary>
public System.Timers.Timer ClientRecentTimer = new System.Timers.Timer();

/// <summary>
/// Socket接收数据状态标识
/// </summary>
public bool ClientIsReg = false;

/// <summary>
/// Object对象
/// </summary>
public object ClientObject = null;

}

#endregion
...全文
305 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
suyiming 2008-08-01
  • 打赏
  • 举报
回复
[Quote=引用 7 楼 lovefootball 的回复:]
哦,好长的Source
在调用控件的地方使用如下代码


C# code
delegate void SetTextCallback(string text);
private void SetText(string text)
{
if (this.Textbox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.Textbox1.Text = text;
}
}
[/Quote]
bluesky880528 2008-08-01
  • 打赏
  • 举报
回复
通过在网上狂搜,我终于把问题解决了。在第一次调用Invoke 或 BeginInvoke之前,加上个判断,如下:
while (!this.IsHandleCreated) { ;}
作用就是在创建窗口句柄没完成之前等待……
谢谢各位!!
yulinlover 2008-07-31
  • 打赏
  • 举报
回复
这是因为你抛出的事件同窗体的控件消息不在一个线程中,.net就这一点非常恶心,你得自己去线程同步。也就是“爱足球”那位先生写的东东。
祝你好运!
bluesky880528 2008-07-31
  • 打赏
  • 举报
回复
lz
在创建窗口句柄之前,不能在控件上调用 Invoke 或 BeginInvoke。
这个问题解决了没?
清风树下 2007-12-03
  • 打赏
  • 举报
回复
改成这种方式调用后,出现以下错误:
在创建窗口句柄之前,不能在控件上调用 Invoke 或 BeginInvoke。
TheRule 2007-11-26
  • 打赏
  • 举报
回复
不是一个线程吧,楼上应该是正解
lovefootball 2007-11-26
  • 打赏
  • 举报
回复
哦,好长的Source
在调用控件的地方使用如下代码


delegate void SetTextCallback(string text);
private void SetText(string text)
{
if (this.Textbox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.Textbox1.Text = text;
}
}

清风树下 2007-11-26
  • 打赏
  • 举报
回复
调用部份
定义: /// <summary>
/// TCP客户端连接
/// </summary>
public TchTcpClient TcpClient = new TchTcpClient();

连接:
this.TcpClient.InfoEvent += new TchInfoEvent(TchClient_TchInfoEvent);
this.TcpClient.InceptEvent += new TchInceptEvent(TchClient_TchInceptEvent);
this.TcpClient.ErrorEvent += new TchErrorEvent(TchClient_TchErrorEvent);
this.TcpClient.SetIPPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Parse(this.Txt_ClinetIP.Text), int.Parse(this.Txt_ClinetPost.Text));
this.TcpClient.StartClient();

返回信息处理:

/// <summary>
/// 数据接收
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void TchClient_TchInceptEvent(object sender, TchInceptEventArgs e)
{
try
{
this.Textbox1.Text=e.GetInceptData;
}
}
catch { } //这里出错,在不是创建该控件的线程中访问。
}
清水心鸣 2007-11-26
  • 打赏
  • 举报
回复
使用Invoke试试
清风树下 2007-11-26
  • 打赏
  • 举报
回复
/// <summary>
/// 异步接收数据
/// </summary>
/// <param name="ar"></param>
private void ReceiveIAsyncResult(IAsyncResult ar)
{
int intCount;
try
{
lock (this.TSInfo.SetClientSocket)
{
intCount = this.TSInfo.SetClientSocket.EndReceive(ar);
}
if (intCount < 1)
{
this.TSInfo.ClientIsReg = false;
this.StopClient(true, true);
return;
}
else
{
this.TSInfo.ClientIsReg = true;
}
this.TSInfo.SetClientDTConnect = DateTime.Now;
this.InceptEvent(this, new TchInceptEventArgs(Encoding.GetEncoding("gb2312").GetString(this.TSInfo.SetClientrecByte, 0, intCount), this.TSInfo));
if (this.TSInfo.ClientIsReg)
{
lock (this.TSInfo.SetClientSocket) { this.Recieve(); }
}
}
catch (Exception Ex)
{
this.ErrorEvent(this, new TchErrorEventArgs(Ex, this.TSInfo));
this.StopClient(false, true);
}
}

/// <summary>
/// 发送信息
/// </summary>
/// <param name="strMsg">信息</param>
public void Send(string strMsg)
{
try
{
if (this.IsConnection)
{
byte[] MessAge = System.Text.Encoding.GetEncoding("gb2312").GetBytes(strMsg.ToCharArray());
try
{
this.TSInfo.SetClientSocket.Send(MessAge);
}
catch (Exception Exp)
{
this.ErrorEvent(this, new TchErrorEventArgs(Exp, this.TSInfo));
this.StopClient(false, true);
}
}
else
{
if (this.TSInfo.SetClientSocket != null)
{
this.ErrorEvent(this, new TchErrorEventArgs(new Exception("发送信息时连接异常断开"), this.TSInfo));
this.StopClient(false, true);
}
}
}
catch (Exception Ex)
{
this.ErrorEvent(this, new TchErrorEventArgs(Ex, this.TSInfo));
this.StopClient(false, true);
}
}

/// <summary>
/// 启动实时监控连接的状态
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void RecentTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
if (this.IsConnection)
{
this.TimerCount++;
if (this.TSInfo.SetClientDTConnect.AddMinutes(this.TSInfo.SetFailureTime) < DateTime.Now) this.StopClient(true, true);
if (this.TSInfo.SetBoolHeartBit)
{
if (this.TimerCount % this.TSInfo.SetIntHeartTime == 0)
{
this.Send(this.TSInfo.SetStrHeartStr);
}
}
}
}
catch (Exception Ex)
{
this.ErrorEvent(this, new TchErrorEventArgs(Ex, this.TSInfo));
this.StopClient(false, true);
}
}

#endregion
}
清风树下 2007-11-26
  • 打赏
  • 举报
回复
#region 方法、启动、停止、异步接收、发送、实时监控
/// <summary>
/// 获取连接状态
/// </summary>
public bool IsConnection
{
get
{
if (this.TSInfo.SetClientSocket == null)
{
return false;
}
else
{
return this.TSInfo.SetClientSocket.Connected;
}
}
}

/// <summary>
/// 启动TCP客户端
/// </summary>
public void StartClient()
{
try
{
if (this.TSInfo.SetClientSocket != null) //当连接启动时停止该连接
{
this.TSInfo.SetClientSocket.Close();
this.TSInfo.SetClientSocket = null;
}
this.TSInfo.SetBool_True = true;
this.TSInfo.SetClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
this.TSInfo.SetClientSocket.Connect(this.IPPoint);
if (this.TSInfo.SetClientSocket.Connected)
{
this.InfoEvent(this, new TchInfoEventArgs("TCP客户端与远程服务器连接成功", this.TSInfo));
this.TSInfo.ClientRecentTimer.Start();

//启动异步接收数据
this.Recieve();

//握手信息
if (this.TSInfo.SetBool_Shake)
{
if (this.TSInfo.SetBool_ShakeCode)
{
this.Send(this.TSInfo.SetStrTxt);
}
else
{
this.Send(this.TSInfo.SetClientID);
}
}
}
else
{
if (this.TSInfo.SetClientSocket != null)
{
this.ErrorEvent(this, new TchErrorEventArgs(new Exception("于目标机器连接成功,在启动异步接收数据时出错"), this.TSInfo));
this.StopClient(false, true);
}
}
}
catch (Exception Ex)//由于目标机器积极拒绝,无法连接。
{
this.ErrorEvent(this, new TchErrorEventArgs(Ex, this.TSInfo));
if (this.TSInfo.SetClientSocket != null)
{
this.StopClient(false, true);
}

}
}

/// <summary>
/// 停止TCP客户端
/// </summary>
/// <param name="SBool">是否提示断开信息</param>
/// <param name="BoolEar">内部关闭True,外部关闭False</param>
private void StopClient(bool SBool, bool BoolEar)
{
if (this.TSInfo.SetBool_True)
{
try
{
try
{
this.TSInfo.ClientIsReg = false;
if (this.TSInfo.ClientRecentTimer != null)
{
this.TSInfo.ClientRecentTimer.Stop();
//this.TSInfo.ClientRecentTimer.Dispose();
}
}
catch (Exception Exp)
{
this.ErrorEvent(this, new TchErrorEventArgs(Exp, this.TSInfo));
}
if (this.TSInfo.SetClientSocket != null)
{
if (SBool) this.ErrorEvent(this, new TchErrorEventArgs(new Exception("TCP客户端与远程服务器连接断开"), this.TSInfo));
if (this.IsConnection) this.TSInfo.SetClientSocket.Shutdown(SocketShutdown.Both);
this.TSInfo.SetClientSocket.Close(); //关闭连接
}
}
catch (Exception Ex)
{
this.ErrorEvent(this, new TchErrorEventArgs(Ex, this.TSInfo));
}
finally
{
this.TSInfo.SetBool_True = false;
this.TSInfo.SetClientSocket = null;
this.TSInfo.ClientObject = null;
}
}
}

/// <summary>
/// 停止TCP客户端
/// </summary>
public void StopClient()
{
this.StopClient(true, false);
}

/// <summary>
/// 启动异步接收
/// </summary>
private void Recieve()
{
if (this.TSInfo.SetClientSocket != null && this.TSInfo.SetClientSocket.Connected)
{
AsyncCallback GetStreamMsgCallback = new AsyncCallback(ReceiveIAsyncResult);
this.TSInfo.SetClientSocket.BeginReceive(this.TSInfo.SetClientrecByte, 0, this.TSInfo.SetByteSize, SocketFlags.None, GetStreamMsgCallback, this);
}
}

清风树下 2007-11-26
  • 打赏
  • 举报
回复
public class TchTcpClient : System.ComponentModel.Component
{
#region 变量定义

/// <summary>
/// Socket连接基本信息
/// </summary>
TchSocketsInfo TSInfo = new TchSocketsInfo();

/// <summary>
/// 心跳使用变量
/// </summary>
private int TimerCount = 0;

/// <summary>
/// 获取/设置Socket连接基本信息
/// </summary>
public TchSocketsInfo SetTSInfo
{
set { this.TSInfo = value; }
get { return this.TSInfo; }
}

/// <summary>
/// 连接服务器的IP地址和端口号
/// </summary>
private IPEndPoint IPPoint = new IPEndPoint(System.Net.IPAddress.Parse("127.0.0.1"), int.Parse("2008"));

/// <summary>
/// 获取/设置连接服务器的IP地址和端口号
/// </summary>
public IPEndPoint SetIPPoint
{
set { this.IPPoint = value; }
get { return this.IPPoint; }
}

/// <summary>
/// 连接接收到数据时触发该事件
/// </summary>
public event TchInceptEvent InceptEvent;

/// <summary>
/// 当连接出现错误时触发该事件
/// </summary>
public event TchErrorEvent ErrorEvent;

/// <summary>
/// 当连接有消息时触发该事件
/// </summary>
public event TchInfoEvent InfoEvent;

#endregion

#region 构造
/// <summary>
/// TCP连接客户端
/// </summary>
/// <param name="IPPoint">服务器的IP地址与端口</param>
public TchTcpClient(IPEndPoint IPPoint)
{
try
{
this.IPPoint = IPPoint;
this.SetClient();
}
catch { }
}

/// <summary>
/// TCP连接客户端
/// </summary>
public TchTcpClient()
{
try
{
this.IPPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), int.Parse("1502"));
this.SetClient();
}
catch { }
}

/// <summary>
/// 设置连接
/// </summary>
private void SetClient()
{
this.TSInfo.SetClientrecByte = new byte[this.TSInfo.SetByteSize];
this.TSInfo.SetClientType = "Client";

//启动实时监控
this.TSInfo.ClientRecentTimer.Interval = 1000;
this.TSInfo.ClientRecentTimer.AutoReset = true;
this.TSInfo.ClientRecentTimer.Elapsed += new System.Timers.ElapsedEventHandler(RecentTimer_Elapsed);
this.TSInfo.ClientRecentTimer.Stop();
}
#endregion
清风树下 2007-11-26
  • 打赏
  • 举报
回复

#region 事件定义

/// <summary>
/// 接收事件信息定义
/// </summary>
public class TchInceptEventArgs : EventArgs
{
/// <summary>
/// 接收数据
/// </summary>
private readonly string InceptData;

/// <summary>
/// Sockets基本信息
/// </summary>
private readonly TchSocketsInfo ClientInfo;


/// <summary>
/// 构造
/// </summary>
/// <param name="InceptData">接收数据</param>
/// <param name="ClientInfo">Sockets基本信息</param>
public TchInceptEventArgs(string InceptData, TchSocketsInfo ClientInfo)
{
this.InceptData = InceptData;
this.ClientInfo = ClientInfo;
}

/// <summary>
/// 获取接收数据
/// </summary>
public string GetInceptData
{
get { return InceptData; }
}

/// <summary>
/// 获取Sockets基本信息
/// </summary>
public TchSocketsInfo GetClientInfo
{
get { return ClientInfo; }
}

}

/// <summary>
/// 接收数据委托
/// </summary>
/// <param name="sender">提供Sockets连接对象</param>
/// <param name="e">接收事件</param>
public delegate void TchInceptEvent(object sender, TchInceptEventArgs e);

/// <summary>
/// 消息信息事件信息定义
/// </summary>
public class TchInfoEventArgs : EventArgs
{
/// <summary>
/// 接收消息信息
/// </summary>
private readonly string InfoData;

/// <summary>
/// Sockets基本信息
/// </summary>
private readonly TchSocketsInfo ClientInfo;

/// <summary>
/// 构造
/// </summary>
/// <param name="InfoData">接收消息信息</param>
/// <param name="ClientInfo">Sockets基本信息</param>
public TchInfoEventArgs(string InfoData, TchSocketsInfo ClientInfo)
{
this.InfoData = InfoData;
this.ClientInfo = ClientInfo;
}

/// <summary>
/// 获取接收消息信息
/// </summary>
public string GetInfoData
{
get { return InfoData; }
}

/// <summary>
/// 获取Sockets基本信息
/// </summary>
public TchSocketsInfo GetClientInfo
{
get { return ClientInfo; }
}
}

/// <summary>
/// 接收消息信息委托
/// </summary>
/// <param name="sender">提供Sockets连接对象</param>
/// <param name="e">消息信息事件</param>
public delegate void TchInfoEvent(object sender, TchInfoEventArgs e);

/// <summary>
/// 错误事件信息定义
/// </summary>
public class TchErrorEventArgs : EventArgs
{
/// <summary>
/// 错误数据
/// </summary>
private readonly Exception ErrorInfo;

/// <summary>
/// Sockets基本信息
/// </summary>
private readonly TchSocketsInfo ClientInfo;


/// <summary>
/// 构造
/// </summary>
/// <param name="Error">错误数据</param>
/// <param name="ClientInfo">Sockets基本信息</param>
public TchErrorEventArgs(Exception Error, TchSocketsInfo ClientInfo)
{
this.ErrorInfo = Error;
this.ClientInfo = ClientInfo;
}

/// <summary>
/// 获取错误数据
/// </summary>
public Exception GetErrorInfo
{
get { return this.ErrorInfo; }
}

/// <summary>
/// 获取Sockets基本信息
/// </summary>
public TchSocketsInfo GetClientInfo
{
get { return ClientInfo; }
}
}

/// <summary>
/// 错误事件委托
/// </summary>
/// <param name="sender">提供Sockets连接对象</param>
/// <param name="e">错误事件信息</param>
public delegate void TchErrorEvent(object sender, TchErrorEventArgs e);
#endregion

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧