在多线程环境下使用udpclient进行异步UDP接收出现“访问已注销对象”的异常,怎么办? 5C

最近打算使用C#写一个仿飞秋的局域网即时通信工具,但是在使用多线程异步收发UDP数据时老是出现“访问对象已注销”的异常,查了好久都没有找到原因,只能求助于网友啦。
完整代码可以在我的github上下载:WAW
说说具体情况吧:
1.为了进行udp数据的异步接收,我写了一个异步接收类AsyncUDPclient。

  public class AsyncUDPclient
    {
        private IPEndPoint recEP, sendEP;
        private UdpClient udpReceive, udpSend;
        private UdpState udpReceiveState, udpSendState;

        //定义消息接收事件
        public event MessageReceivedEventHandle MessageReceived;

        // 异步状态同步
        //private ManualResetEvent sendDone = new ManualResetEvent(false);
        //private ManualResetEvent receiveDone = new ManualResetEvent(false);

        public AsyncUDPclient()
        {
            recEP = new IPEndPoint(IPAddress.Any, InfoSet.IpPort.Port);//允许从任意远程主机终节点接收数据
            sendEP = new IPEndPoint(IPAddress.Any, InfoSet.IpPort.Port);//允许向任意远程主机终节点发送数据,发送和接收使用同一个端口
            udpReceive = new UdpClient(recEP);
            udpSend = new UdpClient();

            udpReceiveState = new UdpState();
            udpReceiveState.udpClient = udpReceive;
            udpReceiveState.ipEndPoint = recEP;

            udpSendState = new UdpState();
            udpSendState.udpClient = udpSend;
            udpSendState.ipEndPoint = sendEP;
        }

        public void ReceiveMsg()
        {
            udpReceive.BeginReceive(new AsyncCallback(ReceiveCallback), udpReceiveState);
            //receiveDone.WaitOne();
        }

        private void ReceiveCallback(IAsyncResult iar)
        {
            UdpState s = iar.AsyncState as UdpState;
            if(iar.IsCompleted)
            {
                IPEndPoint ep = s.ipEndPoint;
                UdpClient u = s.udpClient;
                Byte[] receiveBytes = u.EndReceive(iar, ref ep);

                //调用消息接收事件处理方法
                MessageEventArgs args = new MessageEventArgs();
                args.remoteIP = ep;
                args.buffer = receiveBytes;
                if (MessageReceived != null)
                {
                    MessageReceived(this, args);
                }
                //receiveDone.Set();

                u.BeginReceive(new AsyncCallback(ReceiveCallback), s);//此处需要验证s.ipEndPoint的值是否已经变化?
            }
        }

        public void SendMsg(byte[] datagram,int bytes,IPEndPoint sendEP)
        {
            udpSendState.ipEndPoint = sendEP;
            udpSend.BeginSend(datagram, bytes,sendEP, new AsyncCallback(SendCallback), udpSendState);
            Thread.Sleep(100);
        }

        private void SendCallback(IAsyncResult iar)
        {
            UdpState s = iar.AsyncState as UdpState;
            s.udpClient.EndSend(iar);
            //sendDone.Set();
        }

        public void StopClient()
        {
            udpSend.Close();
            udpReceive.Close();
            Thread.Sleep(100);
        }
    }

    /// <summary>
    /// 消息接收事件委托
    /// </summary>
    /// <param name="Sender"></param>
    /// <param name="e"></param>
    public delegate void MessageReceivedEventHandle(object Sender, MessageEventArgs e);
    public class MessageEventArgs : EventArgs
    {
        public byte[] buffer;
        public IPEndPoint remoteIP;

        public MessageEventArgs() : base()
        {
            remoteIP = new IPEndPoint(IPAddress.Any, 0);
        }
    }
    public class UdpState
    {
        public UdpClient udpClient;
        public IPEndPoint ipEndPoint;
    }

2.当程序启动之后,在程序主窗口类frmMain.cs里开了一个新线程监听指定端口,用于接收UDP数据,然后主窗口程序广播上线消息。

     public partial class frmMain : Form
    {
        //用于整个程序收发数据的对象
        public AsyncUDPclient AsyncUDP;

        private Thread udplistenthread;
        private DataReceive startreceive;

        public frmMain()
        {
            InitializeComponent();
            _userstate = wawState.SignIn;
            Rectangle rec = Screen.GetWorkingArea(this);
            this.ClientSize = new Size(234, rec.Height - 100);
            this.Location = new Point((int)(rec.Width * 0.8), (int)(rec.Height * 0.05));
            this.MaximumSize = new Size(260, rec.Height);
            this.MinimumSize = new Size(234, 100);
            this.chTag.Width = 0;
            this.chUser.Width = (int)(this.lvwUsers.Width * 0.3);
            this.chIP.Width = (int)(this.lvwUsers.Width * 0.4);
            this.chHostname.Width = this.lvwUsers.Width - this.chUser.Width - this.chHostname.Width;

            AsyncUDP = new AsyncUDPclient();//收发数据对象初始化
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            //开启监听线程,新线程执行StartListenUdp方法
            startreceive = new DataReceive(lvwUsers, lblUserCount,AsyncUDP);
            udplistenthread = new Thread(new ThreadStart(startreceive.StartListenUdp));
            udplistenthread.IsBackground = true;
            udplistenthread.Start();

            MsgBoardCast boardcast = new MsgBoardCast(AsyncUDP);
            //boardcast.BoardCast(wawCMD.WAW_BC_SIGNIN);

            int i = 0;
            foreach(IPAddress addr in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
            {
                if(addr.AddressFamily==AddressFamily.InterNetwork)
                {
                    cmbIpList.Items.Add(addr.ToString());
                    if (addr.ToString()==InfoSet.IpPort.Address.ToString())
                    {
                        cmbIpList.SelectedIndex = i;
                    }
                    i++;                    
                }
            }
        }
        }

StartListenUdp方法如下(就是调用异步接收类AsyncUDPclient的ReceiveMsg方法开始异步接收):

        public void StartListenUdp()
        {          
            AsyncClient.MessageReceived += new MessageReceivedEventHandle(DataConfig);
            AsyncClient.ReceiveMsg();
        }

但是在运行过程中一直很出现异常,貌似是说调用udpclient对象是该对象已经注销,但我检查了很久都没有查处问题,这个问题一直卡了我整整两周时间,实在是没办法了。
以下是调试报错截图:
图片说明

3个回答

可以考虑在 udpReceive.Close(); 后设置一个变量,然后在ReceiveCallback check一下这个变量确定要访问的对象是否已经被释放

shangjindetudou
3-_-3 我调试过了,只要是跳到ReceiveCallback回调函数中,变量就是null,我最近在考虑是不是此类调用不能在多线程下使用啊?
大约一年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
使用UDPClient进行传输
假设电脑A(192.168.1.2)和电脑B(192.138.1.20)进行通信,使用UDP协议,使用UDPClient进行编程,端口1234rnrn1.如果我要从A机传一张BMP图片到B,要如何操作?看了很多介绍的例子,都是用文字来演示,发几句话,我不知道如何传非文字,谢谢rnrn2.我们网络是ADSL,多人使用路由器上网,如何能取得我们的外网地址?
关于UDPClient异步发送和接收的问题。
我想问下,UDPClient异步接收如何实现。rn[code=csharp]rnprivate static void InitializeUdpClient() rn IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 11000);rn UdpClient udpClient = new UdpClient(RemoteIpEndPoint);rn //如果这里写while(true) 则会不停挂起异步接收操作,直到占满缓冲区间或队列。会报“由于系统缓冲区空间不足或队列已满,不能执行套接字上的操作”的错rn UdpState s = new UdpState(udpClient, RemoteIpEndPoint);rn udpClient.BeginReceive(EndReceive, s);rn rn private static void EndReceive(IAsyncResult ar) rn try rn UdpState s = ar.AsyncState as UdpState;rn if (s != null) rn UdpClient udpClient = s.UdpClient;rnrn IPEndPoint ip = s.IP;rn Byte[] receiveBytes = udpClient.EndReceive(ar, ref ip);rn string msg = Encoding.UTF8.GetString(receiveBytes);rn udpClient.BeginReceive(EndReceive, s);//在这里重新开始一个异步接收,用于处理下一个网络请求rn rn catch (Exception) rn //处理异常rn rn rn[/code]rn如果是同步接收,可以使用While(true)循环进行验证。如果异步的话,如何开启接收呢。就是代码中InitializeUdpClient函数如何使用?rn如果想接收,直接调用该函数么?调用之后,如果有消息到来,如何验证啊?求教!
UDP 数据接收异常
程序主要是是通过UDP 端口接收数据, 接收几天后就收不到数据了,此时查看发送端,可以确定发送端确实有数据发送出来,但是为什么接收端接收不到数据呢? 接收端程序重启后又可以接收到数据了,总是这样周而复始。是不是接收端口当掉了???rn 请大牛们帮忙参谋参谋!
Udp接收和发送的多线程进行(新手)
以多线程来接收和发送数据(udp) 思路:建立三个函数,一个是发送函数,另一个是接收函数,还有一个主函数,调用前面两个函数,实现功能。在mNetAssist软件下调试。 结果:与非多线程似乎没有什么区别,看了一下思路,没什么错误,等明天再继续看看程序。程序在下面: import socket import threading def send_udp(udp_socket):# nu...
多线程UDP接收!
描述如下:rnrn 接收多个Ip地址发送的数据,并进行处理。怎么实现 ?rnrn 开发环境:vs 2010 C#
C# UDP 异步接收消息
最近想写一个关于局域网通信的工具,用到UDP接收消息时,不能实现异步接收。求哥哥姐姐们帮改一下下面的例子,达到这种效果:只有有广播,就会自动接收。小弟感激不尽rnrn Socket sock = new Socket(AddressFamily.InterNetwork,rn SocketType.Dgram, ProtocolType.Udp);rn IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);rn sock.Bind(iep);rn EndPoint ep = (EndPoint)iep;rn byte[] data = new byte[1024];rn int recv = 0;rn recv = sock.ReceiveFrom(data, ref ep);rn string request = Encoding.Default.GetString(data, 0, recv);rn textBox1.AppendText(request);rnrn这个只能按一下,接收一次,如果用while(true)循环,效果超级不理想。网上都说用异步传输,可是小弟不太懂,求帮改一下这段代码。。
关于UDP 异步接收的问题
我有一个服务端,是使用UdpClient异步接收来自客户端的加密数据。rnrn每当我开启服务端,初期正常,但过一段时间后,加密数据包就变得不正常了,无法正常解密数据了。rn正让我很摸不着头脑。rnrn我自己琢磨会不会是下面的地方出了问题。rnrn因为我是异步接收,我同时投递了多次beginrecvrnrn而在endrecv这里我并没有进行同步锁定,多次重入导致问题。(但这里我都是局部变量,这些是不影响的)rnrn会不会是底层接收缓存在多次线程切换中导致我在endrecv读取出现问题?rnrn请问高手,有这种可能吗?rnrn希望有经验的高人指点迷津
关于UDP异步接收的问题
做一个服务端程序,想从2000端口通过异步接收数据,客户端每隔25秒就会向服务端的2000端口发送数据,但是执行完BeginReceiveFrom之后,OnReceiveComplete却不会被执行,不知道怎么回事,希望各位能帮个忙,多多指教,非常感谢!rnrnrnPrivate Sub ReceiveFromAny()rn Tryrn RemoteEP.Address = IPAddress.Anyrn RemoteEP.Port = 0rn sock.BeginReceiveFrom(Buf, 0, 527, SocketFlags.None, RemoteEP, AddressOf OnReceiveComplete, sock)rn 'RemoteEP = Nothingrn Catch ex As Exceptionrn RaiseEvent OnMessage(ex.ToString)rn End Tryrn End SubrnrnrnPrivate Sub OnReceiveComplete(ByVal ar As IAsyncResult)rn Tryrn RemoteEP.Address = IPAddress.Anyrn RemoteEP.Port = 0rn Dim bytes As Integerrn bytes = sock.EndReceiveFrom(ar, RemoteEP)rn Dim Data(bytes - 1) As Bytern Data.Copy(Buf, 0, Data, 0, bytes)rn RaiseEvent OnReceive(RemoteEP, Data)rn 'RemoteEP = Nothingrn ListenTimer.Enabled = Truern Catch ex As Exceptionrn RaiseEvent OnMessage(ex.ToString)rn End Tryrn End Sub
连接的UDP接收异步错误问题
在网上看见一篇文章,介绍连接的UDP接收异步错误,于是在自己电脑上建立了连接的UDP,使用send()函数发送数据,rnrnrn代码如下:rn[code=c]//创建连接的UDPrn struct sockaddr_in UdpAddr;rn memset(&UdpAddr, 0, sizeof(UdpAddr));rn UdpAddr.sin_addr.S_un.S_addr = inet_addr("192.168.100.200");rn UdpAddr.sin_family = AF_INET;rn UdpAddr.sin_port = htons(8888);rnrn SOCKET UdpSocket = socket(AF_INET, SOCK_DGRAM, 0);rn rn connect(UdpSocket, (struct sockaddr *)&UdpAddr, sizeof(struct sockaddr));rnrn char szSendBuf[] = "HelloWorld";rn for(int i = 0; i < 5; i++)rn rn nRet = send(UdpSocket, szSendBuf, strlen(szSendBuf), 0);rn if(SOCKET_ERROR == nRet)rn rn printf("ErrorId:%d\n", WSAGetLastError());rn rn Sleep(10);rn [/code]rnrn运行发现,192.168.100.200是一个不存在的IP地址,但send()函数却没有返回SOCKET_ERROR错误,感觉send()函数只是将数据拷贝到发送缓冲区中就立即返回了,而无法捕获到ICMP这个异步错误,后来我用抓包工作抓了一下,发送的5个UDP数据包都能抓包,却没有抓到相应的ICMP数据包。rnrnrn于是怀疑帖子中讲解的应该针对LINUX平台,在WinSock中,这种连接的UDP是无法捕获到异步错误,还是说我的理解或代码写的有问题,望大家指教一下!
TCP/UDP异步发送接收
TCP/UDP异步发送接收 实例代码!
UDP异步多线程服务器和客户端程序
UDP异步,多线程服务器和客户端程序,自测支持,收发包率接近与winshark 抓包结果,基于控制台程序。vs2010开发
VC++2010环境,UDP异步套接字编程
VC++ 2010 环境下 UDP异步套接字通信示例
redis多线程访问,出现socket close异常
redis多线程访问,出现socket close异常 rabbitmq出现生产者发送一条数据,但是消费者接受到两条信息
udp 多线程文件接收 问题
兄弟最近在做组播udp 文件传输开发:rnrn思路是:rnrn服务器端 每次读取一个文件的一小部分,组成一个数据包发送出去,然后在继续读下一小块文件。。。以此类推进行发送数据。rnrn客户端采用多线程机制来接收数据,进而实现可靠传输rn创建两个线程:rnrn 第1个线程负责从socket 端 ,recvfrom 接收数据包,并将其写入缓冲区(两个缓冲区);,当缓冲区满了时,发送信号通知另个线程对其进行校验,写入磁盘,同时用另一个缓冲区开始接收数据;rnrn 第2个线程负责将缓冲区数据满的时候,对缓冲区的数据单元进行校验,检查是否有编号为空的数据包,记录丢失数据包的编号,然后将缓冲区的数据写入文件,以此实现文件的接收。rnrn遇到的问题: rnrn在接收数据的时候,会偶尔出现数据包的连续丢失,一段一段的,丢失的编号是随机的,应该不是网络的问题(我测过),可能是多线程没有协调好相互关系,导致接收数据时溢出的原因;在单核cpu下做测试时,丢失数据包更多。rnrnrn个人分析是一个cpu缓冲区数据进行校验、写入文件占用cpu,从网络中实时接收数据也需要cpu 是不是出现写文件时占用cpu时间长而使得接收产生溢出呢?rnrn在双核下测试 性能能好一些 但是要是发送速度达到8M/s 以上时还是存在丢失数据包的问题。rnrn(缓冲区大约15M)rnrnrnrn疑问: 不知道那位兄弟有更好的多线程协调策略或者类似的开发经验能给提供一些 ,非常感谢!rnrnrnrnrnrnrnrnrnrnrn
C# UDP多线程发送接收
通过多线程的方式实现了UDP收发数据 可以快速学习UDP通讯原理应进行实际应用
使用udp进行数据的发送和接收
public class SendDemo { public static void main(String[] args) throws IOException { // 创建发送端Socket对象 DatagramSocket datagramSocket = new DatagramSocket(); // 创建数据,并把数据打包 byte[] ...
请教使用UDP异步收发数据时出现的“无法访问已释放的对象”错误?
我在代码中使用UDP来异步收发数据,但收发语句部分总是提示“无法访问已释放的对象”,请问这是什么原因?代码在下面,请朋友们帮我看看rnprivate void Start()rnrn IPEndPoint ep = new IPEndPoint(IPAddress.Any, channel.Port);rn while (true)rn rn if (!usingSocket)rn rn lock (udp)rn rn AsyncCallback callback = new AsyncCallback(ReceiveCallback);rn udp.BeginReceive(callback, ep);rn usingSocket = true;rn rn rn Thread.Sleep(0);rn rnrn/// rn/// 接收数据的回调方法rn/// rn/// rnprivate void ReceiveCallback(IAsyncResult ar)rnrn lock (udp)rn rn IPEndPoint ep = (IPEndPoint)ar.AsyncState;rn SomeData data = SomeHelper.ReadBytes(udp.EndReceive(ar, ref ep));rn usingSocket = false;rn SaveData(data);rn rnrn
在线程中使用已打开的FileWriter对象,出现运行异常
[code=Java]rnimport java.io.*;rnclass TestFileWriterrnrn static FileWriter fw;rn public static void main(String[] args)rn rn tryrn fw = new FileWriter("1.txt");rn // fw.write("hello"); rn Test test = new Test();rn test.start();rn fw.close();rn rn catch(IOException e)rn rn e.printStackTrace();rn rn rn static class Test extends Threadrn rn @Overridern public void run()rn tryrn fw.write("hello");rn rn catch(IOException e)rn rn e.printStackTrace();rn rn rn rnrn[/code]rnrn编译后运行:rnE:\java\test>java TestFileWriterrnjava.io.IOException: Stream closedrn at sun.nio.cs.StreamEncoder.ensureOpen(Unknown Source)rn at sun.nio.cs.StreamEncoder.write(Unknown Source)rn at sun.nio.cs.StreamEncoder.write(Unknown Source)rn at java.io.OutputStreamWriter.write(Unknown Source)rn at java.io.Writer.write(Unknown Source)rn at TestFileWriter$Test.run(TestFileWriter.java:24)rnrn那么怎样才能传递给线程一个打开的FileWrite 对象,以供使用呢?rn谢谢!
C#多线程访问异常
描述:在一个.cs文件中rnpublic class Arnrn private static object mutexObject = new object(); rn //.....rn public static void Fuction(class b)rn rn lock (mutexObject)rn rn //SQL BeginTransaction(IsolationLevel.ReadUncommitted)rn //此处处理多个delete和update语句rn rn rnrn系统中的两个线程各自的一个方法均调用了该类的这个静态方法,第一个线程是个轮询线程,每次执行时间大概在3S左右,每隔12分钟执行一次,第二个线程经常报错rn错误提示: New transaction is not allowed because there are other threads running in the session. rn这是完整的异常代码rn(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning() at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) at System.Data.SqlClient.TdsParser.TdsExecuteTransactionManagerRequest(Byte[] buffer, TransactionManagerRequestType request, String transactionName, TransactionManagerIsolationLevel isoLevel, Int32 timeout, SqlInternalTransaction transaction, TdsParserStateObject stateObj, Boolean isDelegateControlRequest) at System.Data.SqlClient.SqlInternalConnectionTds.ExecuteTransactionYukon(TransactionRequest transactionRequest, String transactionName, IsolationLevel iso, SqlInternalTransaction internalTransaction, Boolean isDelegateControlRequest) at System.Data.SqlClient.SqlInternalConnection.BeginSqlTransaction(IsolationLevel iso, String transactionName) at System.Data.SqlClient.SqlConnection.BeginTransaction(IsolationLevel iso, String transactionName) at CavalryOLServer.BGameTick.DeleteCityDetailInfo(CityInfoDetail cityDto) at CavalryOLServer.WorldServer.DeleteCityInfo(SqlCommand Comm, CityInfoDetail dto) at CavalryOLServer.LBattleCalculate.CalculatePlayerBattle(SqlConnection Conn, BattleInfoDto dto) at CavalryOLServer.LBattleCalculate.CalculateBattle(SqlConnection Conn, BattleInfoDto dto) at CavalryOLServer.BattleServer.CaculateBattle(SqlConnection Conn) : New transaction is not allowed because there are other threads running in the session.rn现在连第一个线程也报错,错误类型也是一样的,只是错误的调用的地方改为该线程的调用处rn1、我想问lock 在此处是否起作用了,如果起了作用为何会进入代码块报此错误rn2、如果想解决该问题,有没有什么好的办法rn补充:此问题在微软官方有类似的框架异常,但是此处的问题只是在数据量很大的情况下发生,不是单独执行下的必然错误,本机调试没有问题!希望各位达人帮忙解决下
CXF+Spring多线程访问异常
我用CXF2.2.5和Spring2.5.5开发web service,我用80以内个线程访问这个web service没有问题,当线程数提高到100时,报以下异常:rn[code=Java]rnException in thread "Thread-66" Exception in thread "Thread-9" org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Failed to import bean definitions from URL location [classpath:META-INF/cxf/cxf.xml]rnOffending resource: class path resource [beans-client.xml]; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML document from class path resource [META-INF/cxf/cxf.xml]; nested exception is java.lang.OutOfMemoryError: Java heap spacern at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:68)rn at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:85)rn at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:76)rn at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.importBeanDefinitionResource(DefaultBeanDefinitionDocumentReader.java:182)rn at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseDefaultElement(DefaultBeanDefinitionDocumentReader.java:147)rn at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:132)rn at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:92)rn at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:507)rn at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:398)rn at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:342)rn at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:310)rn at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143)rn at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:178)rn at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:149)rn at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:212)rn at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:113)rn at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:80)rn at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:123)rn at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:423)rn at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:353)rn at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139)rn at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:83)rn at com.game.sohu.client.Client.getClient(Client.java:23)rn at com.game.sohu.client.ThreadTest.run(ThreadTest.java:18)rnCaused by: org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML document from class path resource [META-INF/cxf/cxf.xml]; nested exception is java.lang.OutOfMemoryError: Java heap spacern at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:420)rn at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:342)rn at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:310)rn at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143)rn at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:178)rn at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.importBeanDefinitionResource(DefaultBeanDefinitionDocumentReader.java:174)rn ... 20 morernCaused by: java.lang.OutOfMemoryError: Java heap spacern at com.sun.org.apache.xerces.internal.impl.dtd.models.CMNode.firstPos(CMNode.java:96)rn at com.sun.org.apache.xerces.internal.impl.xs.models.XSCMBinOp.calcFirstPos(XSCMBinOp.java:127)rn at com.sun.org.apache.xerces.internal.impl.dtd.models.CMNode.firstPos(CMNode.java:97)rn at com.sun.org.apache.xerces.internal.impl.xs.models.XSCMBinOp.calcFirstPos(XSCMBinOp.java:127)rn at com.sun.org.apache.xerces.internal.impl.dtd.models.CMNode.firstPos(CMNode.java:97)rn at com.sun.org.apache.xerces.internal.impl.xs.models.XSCMBinOp.calcFirstPos(XSCMBinOp.java:127)rn at com.sun.org.apache.xerces.internal.impl.dtd.models.CMNode.firstPos(CMNode.java:97)rn at com.sun.org.apache.xerces.internal.impl.xs.models.XSCMBinOp.calcFirstPos(XSCMBinOp.java:127)rn at com.sun.org.apache.xerces.internal.impl.dtd.models.CMNode.firstPos(CMNode.java:97)rn at com.sun.org.apache.xerces.internal.impl.xs.models.XSCMBinOp.calcFirstPos(XSCMBinOp.java:127)rn at com.sun.org.apache.xerces.internal.impl.dtd.models.CMNode.firstPos(CMNode.java:97)rn at com.sun.org.apache.xerces.internal.impl.xs.models.XSCMBinOp.calcFirstPos(XSCMBinOp.java:127)rn at com.sun.org.apache.xerces.internal.impl.dtd.models.CMNode.firstPos(CMNode.java:97)rn at com.sun.org.apache.xerces.internal.impl.xs.models.XSCMUniOp.calcFirstPos(XSCMUniOp.java:118)rn at com.sun.org.apache.xerces.internal.impl.dtd.models.CMNode.firstPos(CMNode.java:97)rn at com.sun.org.apache.xerces.internal.impl.xs.models.XSDFACM.calcFollowList(XSDFACM.java:745)rn at com.sun.org.apache.xerces.internal.impl.xs.models.XSDFACM.calcFollowList(XSDFACM.java:716)rn at com.sun.org.apache.xerces.internal.impl.xs.models.XSDFACM.calcFollowList(XSDFACM.java:715)rn at com.sun.org.apache.xerces.internal.impl.xs.models.XSDFACM.buildDFA(XSDFACM.java:438)rn at com.sun.org.apache.xerces.internal.impl.xs.models.XSDFACM.(XSDFACM.java:222)rn at com.sun.org.apache.xerces.internal.impl.xs.models.CMBuilder.createDFACM(CMBuilder.java:171)rn at com.sun.org.apache.xerces.internal.impl.xs.models.CMBuilder.getContentModel(CMBuilder.java:131)rn at com.sun.org.apache.xerces.internal.impl.xs.XSComplexTypeDecl.getContentModel(XSComplexTypeDecl.java:185)rn at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(XMLSchemaValidator.java:2065)rn at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.emptyElement(XMLSchemaValidator.java:725)rn at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:322)rn at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(XMLDocumentFragmentScannerImpl.java:1693)rn at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:368)rn at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:834)rn at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:764)rn at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:148)rn at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:250)rn[/code]rnrn我觉得有可能是我获取bean的方式占用了过多的资源导致的,我是用[code=Java]new ClassPathXmlApplicationContext("beans-client.xml" ).getBean("beanName");[/code]方式获得bean的,但是我没有想到好的解决办法。我把系统变量JAVA_OPTS设置为-Xms64m -Xmx1024m没有解决问题(我的内存是2G)。
多线程访问ADO异常
开发环境:VC2005, ADO(msado.dll版本1132 or 1128),线程数量在10~30之间rn关键点 : 基于对话框的mfc程序,app的initinstance中调用了AfxOleInit(); 所有的ADO数据库访问被封装在一个dll中;每次查询使用一个新连接,每个查询结果采用临时变量,并立即取出数据后关闭;rn问题:rn 1. 每次当两个线程同时进行ado操作时必发异常, 比如线程A在 conn->Execute,线程B在RecordSet.CreateInstance; 线程A的Recordset在GetCollect,线程B的RecordSet在CreateInstance时都会异常;rn 异常发生的函数基本上在Conn->Execute和RecordSet.CreateInstance这两个函数中;rn 后来我对 RecordSet的生成和Conn的查询进行加锁,如下:rn Lock();rn AdoRecordSet rs;rn conn = DBConnPool.GetConnection();rn conn->Execute(strSQL, rs);rn Unlock();rn ...rn use rs;rn rs.Close();rnrn 结果use rs;也会和conn的查询以及rs的createinstance冲突导致异常;rn 最后,整个加到锁里面, 如下rn Lock();rn AdoRecordSet rs;rn conn = DBConnPool.GetConnection();rn conn->Execute(strSQL, rs);rn ...rn use rs;rn rs.Close();rn Unlock();rn 貌似问题可以得到解决;(长时间的运行之后未见异常);rnrn 实在是不能理解,明明是不同的连接和结果集,为什么还要同步呢?rnrn 2. 在网上查资料,有些人说需要在每个线程的线程函数中调用coinitialize和couninitialize,结果我发现在有的机器上,线程函数的第一句调用coinitialize会返回s_ok,而有的机器上却返回s_false,明明是同样的代码,怎么会有这种区别呢?rnrnrn请各位不吝赐教,不胜感激.rn rn rn rn
使用多线程,10个线程,一个异常了怎么办?
使用多线程,10个线程,一个异常了怎么办?rn
如何使用UdpClient异步方式连续接收数据
初用UdpClient通信进行编程,按照msdn中对异步接收的方法例程发现只能接收一次数据,然后就结束掉了,该如何来实现不断地进行数据接收呢?是着加了个循环来不断的调用BeginReceive()无法实现。请指教!在线等待解答。
多线程环境下的高效异步日志系统
多线程双缓冲异步日志 https://github.com/chenlujiu/High-Performence-AsyncLogStream.git Introduction 仿照了MUDUO的日志设计,在原有的基础上做了简化,仅供学习。 Envoirment OS: Ubuntu 14.04 Complier: g++ 4.8 Technical points 异步实现 这个日志模块用于多...
使用多线程实现UDP进行数据的收发
本次虽只有代码部分,但理解起来不会有困难 需要的知识点:1.UDP的基本使用   2,多线程的使用 代码如下: import socket import threading def send(udp_socket,send_ip,send_port): #要发送的数据 send_data = input(&quot;请输入要发送的数据&quot;) udp_socket.sendt...
VB2005中UDPClient 使用接收不到数据
最近在做一个网络通信的测试实验,在上位机上我写了一个发送程序,在单片机上接收成果就回传一个“Test is ok”。可上位机我写的测试程序在两个上位机上都接收不到,请大家帮忙解决以下,代码如下:rn发送端:rnImports System.NetrnImports System.Net.SocketsrnImports SystemrnImports System.TextrnrnPublic Class Form1rn Public UDPClient1 As New UdpClientrn Dim recudpclient As UdpClientrn Public LocalIP As New IPEndPoint(IPAddress.Any, 0)rn Public ThreadReceive As System.Threading.Threadrnrn Public l As Booleanrnrn Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Loadrn Dim s As String, s1 As Stringrn s = System.Net.Dns.GetHostNamern s1 = System.Net.Dns.Resolve(s).AddressList(0).ToStringrn TBID.Text = s1rnrn 'Dim ip As IPAddress = System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName).AddressList.GetValue(0)rnrn 'TBID.Text = LocalIP.Address.ToStringrn 'TBPort.Text = LocalIP.Port.ToStringrn TBDeID.Text = ""rn TBDePort.Text = ""rn RTBSendbuff.Text = ""rn RTBRecbuff.Text = ""rnrn End Subrnrn Private Sub Btsend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btsend.Clickrn Dim glIP As IPAddressrn Dim GLPORT As Integerrnrn Tryrn 's = System.Net.Dns.GetHostAddressesrn rn glIP = IPAddress.Parse(TBID.Text)rn GLPORT = TBPort.Textrn UDPClient1.Connect(glIP, GLPORT)rnrnrn Dim senddata As [Byte]() = Encoding.ASCII.GetBytes(RTBSendbuff.Text)rn UDPClient1.Send(senddata, senddata.Length)rn UDPClient1.Close()rnrn l = Falsern While (Not l)rnrn recudpclient = New System.Net.Sockets.UdpClient(12000)rn rn Dim deIP As IPAddressrn deIP = IPAddress.Parse(TBDeID.Text)rn Dim port As Integerrn port = TBDePort.Textrn Dim recid As New IPEndPoint(deIP, port)rnrn Dim receiveBytes As [Byte]() = recudpclient.Receive(recid)rn Dim strReturnData As String = System.Text.Encoding.Unicode.GetString(receiveBytes)rn If strReturnData = "test is ok" Thenrn l = Truern RTBRecbuff.Text = strReturnData.ToStringrn End Ifrn recudpclient.Close()rnrn End Whilern Catch ex As Exceptionrn Console.WriteLine(ex.Message)rn RTBRecbuff.Text = RTBRecbuff.Text & vbCrLf & ex.Messagern End Tryrn End Subrn rnEnd Classrnrn接收端:rnImports System.NetrnImports System.Net.SocketsrnImports SystemrnImports System.TextrnrnPublic Class Form1rn Public UDPClient1 As New UdpClientrn Dim sendudpclient As UdpClientrn Public LocalIP As New IPEndPoint(IPAddress.Any, 0)rn 'Public ThreadReceive As System.Threading.Thread rn Public l As Booleanrnrn Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Loadrn Dim s As String, s1 As Stringrn s = System.Net.Dns.GetHostNamern s1 = System.Net.Dns.Resolve(s).AddressList(0).ToStringrn TBID.Text = s1rnrn 'Dim ip As IPAddress = System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName).AddressList.GetValue(0)rnrn 'TBID.Text = LocalIP.Address.ToStringrn 'TBPort.Text = LocalIP.Port.ToStringrn TBDeID.Text = ""rn TBDePort.Text = ""rn rnrn End Subrnrnrn Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Clickrn Dim glIP As IPAddressrn Dim GLPORT As Integerrnrn Tryrn 's = System.Net.Dns.GetHostAddressesrnrn glIP = IPAddress.Parse(TBID.Text)rn GLPORT = TBPort.Textrn UDPClient1 = New System.Net.Sockets.UdpClient(11000)rnrn Dim recid As New IPEndPoint(IPAddress.Any, 0)rnrn Dim receiveBytes As [Byte]() = UDPClient1.Receive(recid)rn Dim strReturnData As String = System.Text.Encoding.Unicode.GetString(receiveBytes)rn RTB1.Text = strReturnDatarnrn UDPClient1.Close()rnrn Dim senddata As [Byte]() = Encoding.ASCII.GetBytes("Test is ok")rn sendudpclient.Connect(glIP, GLPORT)rn UDPClient1.Send(senddata, senddata.Length)rn UDPClient1.Close()rn Catch ex As Exceptionrn Console.WriteLine(ex.Message)rn RTB1.Text = RTB1.Text & vbCrLf & ex.Messagern End Tryrn End SubrnEnd Classrnrn我看了好多参考实例,都是这样的,可我的怎么收不到数呢
多线程访问Ole对象出现非法
我在view当中有Ole对象,并且有函数A()和B()rnA()包含Ole对象操作,B()没有rn从其他地方(例如弹出的对话框)中通过rnview的指针直接调用着两个函数,没问题。rn但如果从创建的线程当中这样去访问,rnB()是肯定不会有问题,但调用A()就不行了,rn一旦运行到A()中Ole操作的部分,就会rn报内存访问非法rnrn究竟是怎么回事?
出现这种异常怎么办?!
当我在视图上显示图像,然后点击某一菜单项,试图对图像进行某种处理rn时,弹出一对话框,显示:rn Unhandled exception in readfile1.exe(MSVCRTD.DLL)0xC0000005:rnaccess Violation.rn 按确定则弹出一对话框:rn Find ResoursernPlease enter th path forrn MEMCPY.ASM.rn这种错误该怎么分析呢?!rn谢谢!rn
请教 使用UdpClient接收 Udp数据报的问题:
是一个控制台程序,出现的问题:无法接收到Udp数据。rnrn代码如下:rnusing System;rnusing System.Net;rnusing System.Net.Sockets;rnusing System.Text;rnrnnamespace AcceptUdprnrn /// rn /// Class1 的摘要说明。rn /// rn class UDPMulticastListenerrn rn private static readonly IPAddress GroupAddress=IPAddress.Parse("202.39.243.104");rn private const int GroupPort = 7090;rnrn private static void StartListener()rn rn bool done = false;rn UdpClient listener=new UdpClient();rn IPEndPoint groupEP=new IPEndPoint(GroupAddress,GroupPort);rn tryrn rn rn listener.Connect(groupEP);rn rnrn while(!done)rn rn Console.WriteLine("Waiting for broadcast");rn byte[] bytes=listener.Receive(ref groupEP);rn Console.WriteLine("Received broadcast from 0:\n 1\n",groupEP.ToString(),Encoding.ASCII.GetString(bytes,0,bytes.Length));rn rn rn rn catch(Exception ex)rn rn Console.WriteLine(ex.ToString());rn rnrn rn rnrn /// rn /// 应用程序的主入口点。rn /// rn [STAThread]rn static int Main(string[] args)rn rn //rn // TODO: 在此处添加代码以启动应用程序rn //rn StartListener();rn return 0;rn rn rnrnrn请问那些代码出了问题?rnrn疑问:rn 1) listener 接收Udp数据是一种什么机制? 是不是需要每隔几毫秒就扫描一下端口,还是它每时每刻都在监听?rnrn 2)其中的代码片断:rn while(!done)rn rnrn rn 是什么意思?rn不胜感激!
使用UdpClient怎么总是接收时出问题???
代码:rnUdpClient UdpA=new UdpClient();rnbyte[] sendBytes=Encoding.ASCII.GetBytes("hello");rnrichTextBox1.AppendText("->A "+DateTime.Now+":\r\n"+textBox1.Text+"\r\n");rnUdpA.Connect("127.0.0.1",5);rnUdpA.Send(sendBytes,sendBytes.Length);rnUdpClient UdpB=new UdpClient(5);rnIPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5);rnwhile(true)rnrn byte[] receiveBytes=UdpB.Receive(ref RemoteIpEndPoint);rn string receiveMessage=Encoding.ASCII.GetString(receiveBytes);rn richTextBox1.AppendText("<-A "+DateTime.Now+":\r\n"+receiveMessage+"\r\n");rnrnUdpA.Close(); rnUdpB.Close();
请教,UdpClient异步接收数据的问题!
请教下我C#的UdpClient在发送数据后,采用异步机制接受数据,即rnUdpClient.BeginReceive(),如果服务器开着的就没有问题,如果服务器关闭则提示远程主机强迫关闭了个连接rnUpd是无连接的怎么会出现这种情况?谢谢!
UDPclient异步receive()怎么实现?
请给出c#的原代码,谢谢!
异步多线程访问多个串口?
求资料和解决方案rnrn最好有点源代码看看,谢谢各位!
异步拷贝文件时出异常“访问已关闭文件”
我想使用异步文件读写方式完成文件及文件夹的递归复制rnrn每次运行时会报异常,访问已关闭文件,我每次拷贝一个文件,拷贝完毕关闭fileStream,拷贝下一个时重新new 一个fileStream流。 各位大侠帮帮忙,如能指导一二,在下感激不尽
udpclient异步接收消息时,怎样知道远程主机的IP地址.
udpclient异步接收消息时,怎样知道远程主机的IP地址.
UDP 接收数据同步 异步选择问题
同步加线程rn使用事件并发处理接收到的数据rn public void SyncRecive()rn rn Task listen = new Task(() =>rn rn while (true)rn rn int length = connect.ReceiveFrom(this.packetBuffer, 0, this.packetBuffer.Length, SocketFlags.None, ref this.remoteEndPoint);rn byte[] packet = this.packetBuffer.Unpack(length);rn if (length != active.Length || packet.ToMessage() != active.ToMessage())rn rn this.counter++;rn if (this.ReceiveData != null)rn rn this.ReceiveData(packet, this.remoteEndPoint, null);rn rn rn rn );rn listen.Start();rn rnrn异步rnrn public void AsynRecive()rn rn connect.BeginReceiveFrom(this.packetBuffer, 0, this.packetBuffer.Length, SocketFlags.None, ref this.remoteEndPoint, new AsyncCallback(AsynReciveCallback), null);rn rnrn private void AsynReciveCallback(IAsyncResult asyncResult)rn rn if (asyncResult.IsCompleted)rn rn int length = connect.EndReceiveFrom(asyncResult, ref this.remoteEndPoint);rn byte[] packet = this.packetBuffer.Unpack(length);rn this.counter++;rn if (this.ReceiveData != null)rn rn this.ReceiveData(packet, this.remoteEndPoint, null);rn rn rn this.AsynRecive();rn rnrn同步加线程接收效率明显高于异步 rn这样的情况下使用异步还有优势吗?rnrnrn
UdpClient 异步通讯服务端,求助!!!
我的Udp服务端代码如下:rn svrsocket = new UdpClient(new IPEndPoint(IPAddress.Parse(ServerIp), Port));rn IPEndPoint e = new IPEndPoint(IPAddress.Any, 0);rn UdpState s=new UdpState ();rn s.U =svrsocket ;rn s.E =e ;rn _sendmessage = new SendMessage(svrsocket);rn while (true)rn rn rn rn svrsocket.BeginReceive(new AsyncCallback(RecievData), s);rn _IsRun = true;rn rn rn在程序运行后出现如下提示:rn异常出错在 svrsocket.BeginReceive(new AsyncCallback(RecievData), s);rn异常提示:由于系统缓冲区空间不足或列队已满,不能执行套接字上的操作.rnrn
请问networkstream调用异步接收时,出现objectdisposedexception异常
我编程调用networkStream.BeginRead()异步函数,其回调函数是:rn void AsynNetworkstream(IAsyncResult ar)rn rn tryrn rn NetworkStream recnetworkstream = (NetworkStream)ar.AsyncState;rn int numofbytes;rn numofbytes = recnetworkstream.EndRead(ar);rn while (recnetworkstream.DataAvailable) //有可能接收的字符串比缓存要大,所以循环直至接收完所有rn rn recnetworkstream.BeginRead(recbytes, 0, recbytes.Length, new AsyncCallback(AsynNetworkstream),recnetworkstream);rn rnrn rn catch (SocketException err)rn rn int i1 = err.ErrorCode;rn Addstring(err.Message+"errorcode:"+i1.ToString());rn rn rn调试时程序走到while循环中的recnetworkstream.BeginRead()就出现了异常,说是无法访问已释放的对象,请问这是什么原因.
Udp异步接收问题(高手进来)
高手帮忙把这段代码调通,不胜谢意
多线程对象访问问题
我在一个方法中想释放一个对象,但我怕在释放这个对象的过程中另一个使用该对象的方法正在使用这个对象导致不可预料的错误,请问怎样在释放该对象的方法中阻止其他方法使用该对象
相关热词 c++和c#哪个就业率高 c# 批量动态创建控件 c# 模块和程序集的区别 c# gmap 截图 c# 验证码图片生成类 c# 再次尝试 连接失败 c#开发编写规范 c# 压缩图片好麻烦 c#计算数组中的平均值 c#获取路由参数