实在是找不到相关的例子,看MSDN也搞不明白如何实现,请教大家了!谢谢。

解决方案 »

  1.   

    一种弄不明白,回调函数是如何工作的。比如:
            /// <summary>
            /// 发送数据
            /// </summary>
            /// <param name="handler"></param>
            /// <param name="data"></param>
            public void Send(Socket handler, byte[] data)
            {
                //byte[] byteData = Encoding.ASCII.GetBytes(data);
                handler.BeginSend(data, 0, data.Length, 0,
                     new AsyncCallback(SendCallback), handler);
                
            }                /// <summary>
            /// 发送回调
            /// </summary>
            /// <param name="ar"></param>
            private void SendCallback(IAsyncResult ar)
            {
                try
                {
                    Socket handler = (Socket)ar.AsyncState;
                    int bytesSent = handler.EndSend(ar);
                    handler.Shutdown(SocketShutdown.Both);
                    handler.Close();
                }
                catch (Exception ex)
                {
                    if (sendfail!=null)
                    {
                        sendfail(ex);
                    }
                    
                }
            }
    Send 和 SendCallback 是怎样协同工作的呢?我如何获得已发送的字节数呢?
      

  2.   

    简单点说
    AsyncCallback 本质是个委托
    被调用时引用事件处理方法完成异步过程的任务逻辑
    AsyncCallback引用IAsyncResult接口实现了异步操作的等待和完成等状态
      

  3.   

    楼上的同志们,方便的话来个实例来说明吧!就像我上面贴的代码,我要添加SendDataProgressChanged事件,该如何实现?
      

  4.   

    这里有个不精准的进度条
    接收方记录了一下 还是建议使用上面的方法做合理些try
                    {
                        ChatMsg msgForm = FindForm(file.SendId) as ChatMsg;
                        msgForm.reCount++;
                        if (msgForm.reCount > int.Parse(file.FileSize) / 1024 - 3)
                        {
                            msgForm.progressBar_file.Visible = false;
                        }
                        else
                        {
                            msgForm.progressBar_file.Visible = true;
                            msgForm.progressBar_file.Value = (msgForm.reCount * 100) / (int.Parse(file.FileSize) / 1024);
                        }
                    }
                    catch { }