Application.Run(new MainForm())弹出异常

137867312 2014-04-29 10:09:05

我用C#编写一个收发数据的客户端程序,当客户端运行一段时间后,就弹出上图所示的异常,求各位大牛支招~~~
...全文
629 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
threenewbee 2014-05-01
  • 打赏
  • 举报
回复
代码不全,没有看到构造函数
137867312 2014-04-30
  • 打赏
  • 举报
回复
引用 5 楼 caozhy 的回复:
贴错了,要MainForm的代码。
namespace _IEC
{
    partial class MainForm
    {
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗体设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.btnClient = new System.Windows.Forms.Button();
            this.btnServer = new System.Windows.Forms.Button();
            this.btnExit = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // btnClient
            // 
            this.btnClient.Location = new System.Drawing.Point(52, 29);
            this.btnClient.Name = "btnClient";
            this.btnClient.Size = new System.Drawing.Size(89, 32);
            this.btnClient.TabIndex = 0;
            this.btnClient.Text = "客户端模式";
            this.btnClient.UseVisualStyleBackColor = true;
            this.btnClient.Click += new System.EventHandler(this.btnClient_Click);
            // 
            // btnServer
            // 
            this.btnServer.Location = new System.Drawing.Point(52, 86);
            this.btnServer.Name = "btnServer";
            this.btnServer.Size = new System.Drawing.Size(89, 32);
            this.btnServer.TabIndex = 1;
            this.btnServer.Text = "服务器模式";
            this.btnServer.UseVisualStyleBackColor = true;
            this.btnServer.Click += new System.EventHandler(this.btnServer_Click);
            // 
            // btnExit
            // 
            this.btnExit.Location = new System.Drawing.Point(52, 143);
            this.btnExit.Name = "btnExit";
            this.btnExit.Size = new System.Drawing.Size(89, 32);
            this.btnExit.TabIndex = 2;
            this.btnExit.Text = "退出";
            this.btnExit.UseVisualStyleBackColor = true;
            this.btnExit.Click += new System.EventHandler(this.btnExit_Click);
            // 
            // MainForm
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(203, 210);
            this.Controls.Add(this.btnExit);
            this.Controls.Add(this.btnServer);
            this.Controls.Add(this.btnClient);
            this.Name = "MainForm";
            this.Text = "请选择模式";
            this.Load += new System.EventHandler(this.MainForm_Load);
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.Button btnClient;
        private System.Windows.Forms.Button btnServer;
        private System.Windows.Forms.Button btnExit;
    }
}
137867312 2014-04-30
  • 打赏
  • 举报
回复
引用 6 楼 Z65443344 的回复:
MainForm报错,你贴ClientForm的代码...
初学者,让大神们见笑了
137867312 2014-04-30
  • 打赏
  • 举报
回复
引用 5 楼 caozhy 的回复:
贴错了,要MainForm的代码。
不好意思,MainForm的代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace  _IEC
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }
        private void MainForm_Load(object sender, EventArgs e)
        {

        }
        
        private void btnClient_Click(object sender, EventArgs e)
        {
            ClientForm obj = new ClientForm();
            obj.Show();
        }

        private void btnServer_Click(object sender, EventArgs e)
        {
            //ServerForm obj = new ServerForm();
            //obj.Show();
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
於黾 2014-04-30
  • 打赏
  • 举报
回复
MainForm报错,你贴ClientForm的代码...
threenewbee 2014-04-29
  • 打赏
  • 举报
回复
贴错了,要MainForm的代码。
137867312 2014-04-29
  • 打赏
  • 举报
回复

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;

namespace _IEC
{
    public partial class ClientForm : Form
    {
        private byte[] PackageBuffer = new byte[4096];//定义一个数据缓冲包数组,即4K
        private int PackageBufferLength = 0;//定义一个数据包长度的变量

        private void ShowPackage()//显示报文
        {
            int i;
            string content = "";
            Color Color = rtb.SelectionColor;
            SetTextColor(Color.Blue); 
            for (i = 0; i < (PackageBuffer[1] + 2); i++)
            {
                content += PackageBuffer[i].ToString("X2");
                content += "  ";
            }
           rtb.AppendText("收到的报文为:" + "\r\n" + content + "\r\n");
            SetTextColor(Color);
        }


        public ClientForm()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
        }

        private string data = null;
        private delegate void HandleSaveText(string text);     //定义委托,用于多线程保存文件
        private HandleSaveText handleSave;
        private bool isExit = false;
        private TcpClient tcpclient;
        private NetworkStream netStream;

        private ManualResetEvent allDone = new ManualResetEvent(false);

        private void Connect()
        {
            tcpclient = new TcpClient(AddressFamily.InterNetwork);
  
            AsyncCallback RequestCallBack = new AsyncCallback(requestCallBack);
                        
            allDone.Reset();//将事件线程设置为非终止状态

            tcpclient.BeginConnect(IPAddress.Parse(ServerIP.Text.Trim()), int.Parse(Port.Text.Trim()), requestCallBack, tcpclient);
            
            allDone.WaitOne();
        }

        
        public class dataread
        {
            public NetworkStream netstream;
            public byte[] PackageBuffer;
            public dataread(NetworkStream ns, int buffersize)
            {
                this.netstream = ns;
                this.PackageBuffer = new byte[buffersize];
            }
        }

        private void requestCallBack(IAsyncResult ar)
        {
            allDone.Set();
            tcpclient = (TcpClient)ar.AsyncState;

            if (tcpclient.Connected)
            {
                txtState.Text = "连接服务器成功!";
                
             }
                             
            else
            {
                txtState.Text = "连接服务器失败,请检查服务器地址或端口!";
            }
         }
  
        private void SendCallback(IAsyncResult ar)
        {
            try
            {
                netStream.EndWrite(ar);
            }
            catch (Exception ex)
            {
                txtState.Text = ex.Message;
            }
        }


       private void ReadCallBack(IAsyncResult ar)
        {
            try
            {

                int rec = netStream.EndRead(ar);
                PackageBufferLength = PackageBuffer.Length;
               ShowPackage();
               netStream.BeginRead(PackageBuffer, 0, PackageBuffer.Length, new AsyncCallback(this.ReadCallBack), netStream);

  
            }
            catch (Exception ex)
            {
                txtState.Text = ex.Message;
            }
        }

        private void connect_Click(object sender, EventArgs e)
        {
            try
            {
                Connect();
                connect.Enabled = false;
                Stopconnect.Enabled = true;
                ServerIP.Enabled = false;
                Port.Enabled = false;
                
            }
            catch (Exception ex)
            {
                txtState.Text = ex.Message;
            }
           
        }

        public string byteToHexStr(byte[] bytes)//转化成16进制数
        {
            string returnStr = " ";
            Color Color = rtb.SelectionColor;
            SetTextColor(Color.Blue);
            if (bytes != null)
            {
                for (int i = 0; i < bytes.Length; i++)
                {
                    returnStr += bytes[i].ToString("X2");
                    if (((i + 1) % 6) == 0)
                        returnStr += "  ";
                }
            }
            return returnStr;
        }

   

        private void ClientForm_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
            ServerIP.Text = "192.168.0.106";
            Port.Text = "2404";
            //ServergroupBox.Enabled = false;
            ClientgroupBox.Enabled =true;
        }

        private void Stopconnect_Click(object sender, EventArgs e)
        {
            Stopconnect.Enabled = false;
            connect.Enabled = true;
            ServerIP.Enabled = true;
            Port.Enabled = true;
            tcpclient.Close();
            txtState.Text = "已与服务器断开!";
        }

           rtb.AppendText("主站发送的报文为:" + "\r\n" + str + "\r\n");

            dataread dr = new dataread(netStream, tcpclient.ReceiveBufferSize); //client.receivebuffersize接收缓冲区的大小
            //开始接受数据
            netStream.BeginRead(dr.PackageBuffer, 0, dr.PackageBuffer.Length, new AsyncCallback(ReadCallBack), dr);    
            

        }              

     }
    
}
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace _IEC static class Program { /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } } } [/code] 部分代码如上,刚接触C#不久,麻烦你多多指导,万分感谢
threenewbee 2014-04-29
  • 打赏
  • 举报
回复
引用 2 楼 u014444640 的回复:
是什么原因导致的,我应该怎样修改?现行谢谢
起码你把构造函数的代码贴出来。 这要能看出来,那岂不见鬼了。
137867312 2014-04-29
  • 打赏
  • 举报
回复
是什么原因导致的,我应该怎样修改?现行谢谢
threenewbee 2014-04-29
  • 打赏
  • 举报
回复
MainForm构造函数中有一个变量为null。

110,534

社区成员

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

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

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