S7NetPlus / s7netplus

S7.NET+ -- A .NET library to connect to Siemens Step7 devices
MIT License
1.3k stars 580 forks source link

TimeoutException management in TPKT.ReadAsync #462

Closed CSTTrevisiolPaolo closed 1 year ago

CSTTrevisiolPaolo commented 1 year ago

TPKTInvalidException does't mean TimeoutException ... this manage real TimeoutException.

scamille commented 1 year ago

I'd recommend reading https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/cancel-async-tasks-after-a-period-of-time and https://learn.microsoft.com/en-us/dotnet/api/system.threading.cancellationtokensource.createlinkedtokensource?view=net-7.0

mycroes commented 1 year ago

@CSTTrevisiolPaolo please follow the advice from @scamille. The current code is still blocking the thread. It's actually now waiting on either the task or the passed in cancellationToken, while if cancellation was requested it will now throw a TimeoutException instead of properly handling the cancellation instead.

I'm not sure if you're aware, but you can use a CancellationToken with timeout to achieve what you're trying to do here, except that you won't get a TimeoutException. If that is what you need though, you could catch the OperationCancelledException and throw a TimeoutException with the OperationCancelledException as innerException argument.

I will reconsider this PR if it's still properly async and doesn't break other behavior.

CSTTrevisiolPaolo commented 1 year ago

@mycroes , in last days I use this library for communication in production linking with a S7-1200 CPU and S7-1500 CPU. I've spent much time on understanding of "TPKTInvalidException" customer get ... in debug i found Exception during EstablishConnection function; no problem in RequestConnection call ... but assert during SetupConnection call ... So, first calling in ReadAsync was ok, second call in ReadAsync cause "TPKTInvalidException" ... but really I found a timeout in stream call, and get timeout exeption error ... so I understand there was an error on setting IP Address . Managing TimeoutException help me very much. Using correct IP address all was good, and my software have communication data in writing and reading.