CANhack.de CAN-Interface RKS+CAN
CAN Hardware, CAN Software, CAN Protocols - CAN Bus Forum for Your CAN Bus Project.

Problems accessing the COM port in C#

 
New Topic Reply 🔗 🖨 CANhack.de - Index » CAN Bus General
Author Message
AudiA4B6US
Guest




 


Free account, no CAN development support

Post26-11-2006, 18:52    Subject: Problems accessing the COM port in C# Quote

Hello everyone,

I'm just starting to learn C# (using Visual Studio Express 2005), and I keep running into the same problem. For comparison, I've also written similar code in VB, but the result is the same.

The code below is a simple program that opens the serial port, initializes the CANUSB adapter, and then displays the received strings in a text box. I have linked the 'Open' button to the CANUSB initialization process, so logging starts immediately. Similarly, the 'Close' button tells the CANUSB adapter to stop logging.

The problem is that my program freezes when I click the 'Close' button.
'The button press sometimes works, but roughly every other time it fails. If I remove the line `serialPort1.Write('C');` when closing the program, it takes longer for the program to freeze, but it still eventually freezes after opening and closing it 5-10 times. Switching to a timer instead of the `DataReceived` event also avoids the problem, but I'm not sure if this is the solution to my problem or if it just makes it less obvious.'

'Since I'm just starting out with programming knowledge, I'm naturally a bit confused and would like to hear some opinions on this. Examples in VB6, VB 2005, or C# 2005 would also be helpful. Interestingly, this only happens with my own code. I can connect and disconnect the can tool as many times as I want, but nothing happens.'

I would be grateful for any advice.

Regards,
Dirk.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;

namespace CANTest10
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void btnOpen_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
btnOpen.Text = 'Open';
//reset CAN adapter and close COM port
serialPort1.Write('C ');
serialPort1.Close();
}
else
{
btnOpen.Text = 'Close';
// set COM port parameters and open COM port
serialPort1.PortName = 'COM4';
serialPort1.BaudRate = 115200;
serialPort1.DataBits = 8;
serialPort1.StopBits = StopBits.One;
serialPort1.Parity = Parity.None;
serialPort1.Open();
//init CAN adapter to read all CAN traffic off CAN bus
serialPort1.Write('C S3 Z0 O ');
}
}

private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//if new data arrives in serial port buffer use invoke to display on Windows form
this.Invoke(new EventHandler(ProcessNewData));
}

private void ProcessNewData(object sender, EventArgs e)
{
//read all data received off buffer and display in text box
this.textBox1.Text = serialPort1.ReadExisting();

}
}
}


Translated on 14-07-2026, 8:42.
Back to top
candev
Guest




 


Free account, no CAN development support

Post27-11-2006, 12:27    Subject: Problems accessing the COM port in C# Quote

Hi,

'In my opinion, the problem is likely happening exactly within the `serialPort1.Close()` call. You could test this with the debugger. Set a breakpoint on the `serialPort1.Close()` call and then step through the code line by line. Does it get stuck here, or only when you 'delete' the `SerialPort` object?'

It's unfortunate that your code doesn't include the relevant parts. What's important is how and where you instantiate and dispose of the `serialPort` object, for example.

The problem often relates to resource management. You can't program the same way in interpreted languages and runtime-based languages like C#/Java as you can in C++. In particular, you should make extensive use of the `Dispose` pattern (see Microsoft documentation). As long as you proceed like in VB, C++, or other compiled languages, you will continue to encounter a lot of these problems.

First, determine exactly where the 'hang' is occurring. In my opinion, the program doesn't actually get stuck, but it simply takes a very long time to continue executing. However, you will become quite knowledgeable about dealing with ports through online resources.

'Oh yes, the hanging issue when closing the serial port using `Close()` also occurs in C++. The behavior of the serial driver is, shall we say, not exactly amusing. So, if the `Close()` call is the problem, you'll need to find a workaround yourself. You can fix resource management issues within your own code.'

I'm currently working on my diagnostic tester – partly because of a problem with the connection ('hanger') in the software, but also due to issues with the baud rate switching and the lack of direct bit rate detection capabilities within the hardware itself. This approach causes fewer problems than using the methods provided by Windows (API, OCX), although it requires a device driver to access the hardware.

Best regards,
Jens.


Translated on 14-07-2026, 8:46.
Back to top
candev
Guest




 


Free account, no CAN development support

Post27-11-2006, 13:16    Subject: Problems accessing the COM port in C# Quote

Here's a brief excerpt from the help page for the SerialPort class, specifically regarding the 'Close' member function:

The best practice for any application is to wait for some amount of time after calling the Close method before attempting to call the Open method, as the port may not be closed instantly.

If the 'Close' call is indeed the cause in your case, then you will...
a) we must learn to live with it or...
b) how I personally had to find a solution.

Good luck!
Jens.


Translated on 14-07-2026, 8:49.
Back to top
AudiA4B6US
Guest




 


Free account, no CAN development support

Post27-11-2006, 15:01    Subject: Problems accessing the COM port in C# Quote

Hello Jens,

Thank you for the response. Unfortunately, I've only just started learning C#. I was glad that I could already communicate with the CANUSB adapter using Visual Studio Express 2005 and its drag-and-drop objects. But I'm relieved to know that I'm not the only one experiencing these problems. I haven't dealt with resource management at all yet; I always assumed that the IDE would insert the appropriate code.

I'll follow your suggestion and try to figure out exactly where the program is hanging by stepping through it in debug mode. It definitely always happens when I click 'Close,' regardless of how long the port was open beforehand. Based on what I've seen so far, it seems to happen more frequently when there are a lot of data in the buffer or when the buffer is being read very often per unit of time.

Regards,
Dirk.


Translated on 14-07-2026, 8:51.
Back to top
candev
Guest




 


Free account, no CAN development support

Post27-11-2006, 16:44    Subject: Problems accessing the COM port in C# Quote

Hi Dirk,

Then it's probably definitely the close call on the serial port.

I initially considered rewriting my diagnostic tester to be based on C# (currently it's in C++/MFC). The reason is that I need to connect a new, manufacturer-specific protocol for my Mercedes, as I have only implemented VAG protocols so far (essentially VAG1551 or something similar).

Ich hatte mir erhofft, dass mit der .Net-Runtime nun endlich einmal ein vernuenftiger, funktionierender Zugriff auf den ser. Port moeglich sei. Meine Untersuchungen habe dann schnell gezeigt, dass auch die .Net-Runtime auf dem alten WinAPI-Gelumpe und aufsetzt und damit auch den Serial.sys-Treiber vom Windows verwendet. Dumm gelaufen, denn bis zu 200ms nach Umschalten der Bitrate kann ich mir nicht erlauben. I decided to abandon the porting effort to C# due to a lack of real advantages, but with a significant number of disadvantages related to the garbage collector.

Best regards,
Jens.

PS: You live in a very interesting place - especially for those with an automotive hobby! icon_lol.gif


Translated on 14-07-2026, 8:53.
Back to top
rathma
Guest




 


Free account, no CAN development support

Post01-12-2006, 15:40    Subject: Problems accessing the COM port in C# Quote

@candev
I think that if I read between the lines, I need the same thing you do. I want to send relatively simple (ideally using VB) data at a very slow baud rate (5), and then immediately after (i.e., wait less than 200ms), continue sending and receiving data at a different baud rate. If you have a solution, please post it here or email me.

Best regards.
Markus.


Translated on 14-07-2026, 8:54.
Back to top
candev
Guest




 


Free account, no CAN development support

Post01-12-2006, 20:01    Subject: Problems accessing the COM port in C# Quote

Okay, someone also needs to do a slow initialization under ISO9141 icon_biggrin.gif.

'Unfortunately, based on past experiences with providers of commercial products, I will not be providing the source code or the device driver. Please understand that I don't want to spend years developing something and then have others profit from it. I believe you understand this, and you would likely feel the same way.'

To give you an idea of the effort involved: To my knowledge, I'm the only one who has bit rate detection built into their PC-based diagnostic tester – and that's achieved by measuring the bit lengths. Everyone else needs external hardware (which then includes a timer with input capture functionality) or they 'guess' the baud rate through trial and error. Just implementing this bit rate detection took me 2 years, and it was far from enjoyable...

Best regards,
Jens.


Translated on 14-07-2026, 8:56.
Back to top
e320cdi
Guest




 


Free account, no CAN development support

Post11-12-2006, 0:59    Subject: Problems accessing the COM port in C# Quote

The slow initialization/fast initialization problem can be most easily solved with a bit of creativity and the appropriate interpretation of baud rates that may not seem suitable at first glance.

Especially with Fastinit (25ms low/25ms high), many serial interfaces simply have the problem of not being able to switch from 5 Baud to the required 10400 Baud or whatever is needed subsequently within the necessary time, or the interface is unintentionally re-initialized.

However, if you think about the problem more deeply and potentially even program the RTS/CTS functionality for the interface yourself, there are also solutions available.

Best regards, Mike.


Translated on 14-07-2026, 8:58.
Back to top
candev
Guest




 


Free account, no CAN development support

Post11-12-2006, 20:04    Subject: Problems accessing the COM port in C# Quote

Gerade beim Fastinit (25ms low/25ms high) haben viele serielle Schnittstellen einfach das Problem, die Umschaltung von 5Bd auf die 10400Bd oder was auch immer anschließend benötigt wird nicht in der erforderlichen Zeit hinzubekommen oder die Schnittstelle wird ungewollt neu initialisiert.

Hi Mike,

I don't have to understand that, do I? At least, it's different for me icon_confused.gif.
With Slow-Init, I encounter the problem of bitrate switching (assuming a PC as the platform), while with Fast-Init, I don't have this issue (we can disregard special cases like switching the baud rate in conjunction with software updates and certain 'backdoor' features found in development controllers).

Best regards,
Jens (with only W202.078).


Translated on 14-07-2026, 8:59.
Back to top
e320cdi
Guest




 


Free account, no CAN development support

Post12-12-2006, 1:51    Subject: Problems accessing the COM port in C# Quote

Hello Jens,

I'm encountering issues with the required signal level in SlowInit (specifically for VW/Audi vehicles), while with FastInit (for Mercedes-Benz), the problem lies with the wake-up pattern.

However, I usually don't use PC platforms but microcontroller-based boards with Infineon C164, ATMEL + PHILIPS SJA, or Freescale HCS12.

Best regards, Mike.

P.S.: (211.226)


Translated on 14-07-2026, 9:01.
Back to top
New Topic Reply 🔗 🖨 CANhack.de - Index » CAN Bus General
Similar articles and topics
Topic Forum
No new posts Problems with Extended CAN CAN Software Tools and Software
No new posts tachosignal probleme CAN Bus General
No new posts Probleme Logging CAN-Infotainment und Senden Interior / Comfort CAN
No new posts [Audi] CAN bus issues (navigation deactivation) Interior / Comfort CAN
Jump to:  
You cannot post new topics in this forum.