mercredi 11 mars 2015

Exception Handling in a Windows Forms Application

I'm doing a program for serial communications. To centralize the process of access to serial, created a class.


I am having problem when an exception is lançanda within the class leaves the locked program.


example: When trying aberir the serial port, can give error and the system is at that point to burst memory.


How should I handle errors? Put try and catch? Add another routine?


Error point:



portSerial.Open();


Program



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PortSerial.Lib;

namespace ProgramPortSerial
{
public partial class Form1 : Form {

public static LibPortaSerial portSerial = new LibPortSerial();

public Form1()
{
InitializeComponent();

portSerial.LineReceived += new LineReceivedEventHandler(sp1_LineReceived);
portSerial.Init(
ref cmbPortas,
ref cmbVelocidade,
ref cmbBitsDeDados,
ref cmbPariedade,
ref cmbBitsDeParada,
ref cmbControleDeFluxo);
}

void sp1_LineReceived(object sender, LineReceivedEventArgs Args)
{
// Tem que ser em uma nova thread para não travar
Invoke(new Action(() =>
{
memDadosRecebidos.Text += "\r\n" + Args.Resposta;
}));
}

private void btnAbrirPorta_Click(object sender, EventArgs e)
{
portSerial.Open();
}
}
}


Class PortSerial



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Windows.Forms;

namespace PortSerial.Lib
{

public class LibPortSerial : IDisposable
{
public SerialPort portSerial;

public LibPortSerial()
{
portSerial = new SerialPort();
}

public void Dispose()
{
if (portSerial != null)
portSerial.Dispose();
}


public void Open(
string port,
int veloc,
int bitsData,
string pariedade,
string bitsStop,
string control)
{
portSerial.PortName = port;
portSerial.BaudRate = veloc;
portSerial.DataBits = bitsData;
portSerial.Parity = SetPariedade(pariedade);
portSerial.StopBits = SetBitsStop(bitsStop);
portSerial.Handshake = Setcontrol(control);
portSerial.Open(); // ==> Erro this point
}
}
}

Aucun commentaire:

Enregistrer un commentaire