一个委托的例子,外部多线程访问窗体控件
using System;
using System.Collections.Generic;
using System.Text;
namespace RcaNetwork
{
public class RcaNETServer
{
public delegate void EventBase(string username, string IP, string state);
public static event EventBase ClientConnEvent;
public static void RaiseEvent(string username, string IP, string state)
{
if (ClientConnEvent != null)
{
try
{
ClientConnEvent.BeginInvoke(username, IP, state, null, null);
}
catch { }
}
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace RcaNetwork
{
public class NETBASE : MarshalByRefObject
{
public string GetBLL()
{
RcaNETServer.RaiseEvent("test", "localhot", "LOGIN");
return "OK";
}
}
}
public partial class frmServer : Form
{
public frmServer()
{
InitializeComponent();
}
private void frmServer_Load(object sender, EventArgs e)
{
StartRemoting();
}
private void StartRemoting()
{
RemotingConfiguration.Configure("ServerConfig.xml", false);
RcaNETServer.ClientConnEvent += new RcaNETServer.EventBase(ClientConnection);
}
//客户端连接事件
private delegate void deClientConnection(string username, string IP, string state);
private void ClientConnection(string username, string IP, string state)
{
if (listView1.InvokeRequired)
{
deClientConnection outdelegate = new deClientConnection(ClientConnection);
this.BeginInvoke(outdelegate, new object[] { username, IP, state });
return;
}
if (state == "LOGIN")
{
ListViewItem LvItem = new ListViewItem(IP);
LvItem.SubItems.Add(username);
listView1.Items.Add(LvItem);
}
else
{
for (int i = 0; i < listView1.Items.Count; i++)
{
if (listView1.Items[i].Text == IP)
{
listView1.Items.RemoveAt(i);
}
}
}
}
}


浙公网安备 33010602011771号