vb.net mutex class throw exception error - vb.net

I found error code "The wait completed due to abandoned mutex..Can anyone give me any idea on how to solve it?
Here is the code:
Try
gcLog.log(" UseResource Start[1]")
ltWaitTimeSpan = New System.TimeSpan(0, 0, 20)
gcLog.log(" UseResource Start[3]")
If mut.WaitOne(ltWaitTimeSpan, True) Then
Thread_Status = True
Thread_Status_Chk_Count = 0
gcLog.log(Thread.CurrentThread.Name + " Thread Start !!![2]")
lsWorkInstID = Thread.CurrentThread.Name
gcCommon.IsWorkSheetIDExist(Thread.CurrentThread.Name)
gcMsgQue.mnDisMsgInfo2Label_Active(lsWorkInstID)
gcLog.log(" UseResource Start[2]")
Dim loSeqManage As clsSeqManage
loSeqManage = New clsSeqManage
If Not loSeqManage.bReadMsgFmDb(lsWorkInstID, lsLotID) Then
'gcLog.log(" UseResource Start[3]")
Thread_Status = False
Else
Dim loOutput2Prt As New clsOutput(lsLotID,gtMsgQueueEvent.sCryFileName)
loOutput2Prt.SetVariable()
'gcLog.log(" UseResource Start[4]")
If (loOutput2Prt.Output2PrtAuto And Not loOutput2Prt.GetMoreBatchFlag)
Then
gcLog.log(Thread.CurrentThread.Name + " Delete Record !!!")
Call loOutput2Prt.bDeleteMsgFmBuf()
End If
gcLog.log(Thread.CurrentThread.Name + " Thread Release !!![22]")
Thread_Status = False
mut.ReleaseMutex()
End If
End If
Catch ex As Exception
gcLog.log("UseResource : " + ex.Message & vbLf & ex.TargetSite.Name)
Call gfncCallError("2", "PrintFormServer", "UseResource : " + ex.Message & ""& ex.TargetSite.Name)
Thread_Status = False
End Try

Related

DotRAS.dll not working on Windows 10 Update 1803

I have a small VB.NET program, which creates a VPN connection.
This is working until (and including) Windows 10 Update 1709.
But since the Update 1803 I always get an exception:
DotRas.RasException: An incorrect structure size was detected.
at DotRas.Internal.ThrowHelper.ThrowRasException(Int32 errorCode)
at DotRas.Internal.RasHelper.GetEntryProperties(RasPhoneBook phoneBook, String entryName)
at DotRas.RasEntryCollection.Load()
at DotRas.RasPhoneBook.Open(String phoneBookPath)
Following my working Code Sub (until 1709)
Private Sub CreateVPN(VpnName As String, Destination As String, bAllUsers As Boolean)
Dim PresharedKey As String = "XXXXXXXXXXX"
Try
Dim PhoneBook As New RasPhoneBook
Dim sUsedPhoneBook As String = sPhoneBook
If bAllUsers Then sUsedPhoneBook = sAllUserPhoneBook
PhoneBook.Open(sUsedPhoneBook)
'First remove existing VPN with same name, if exist!
Try
PhoneBook.Entries.Remove(VpnName)
Catch ex As Exception
End Try
Dim VpnEntry As RasEntry = RasEntry.CreateVpnEntry(VpnName, Destination, DotRas.RasVpnStrategy.L2tpOnly, DotRas.RasDevice.Create(VpnName, DotRas.RasDeviceType.Vpn))
VpnEntry.Options.UsePreSharedKey = True
VpnEntry.Options.IPHeaderCompression = True
VpnEntry.Options.SoftwareCompression = True
VpnEntry.Options.NetworkLogOn = True
VpnEntry.NetworkProtocols.IPv6 = False
VpnEntry.Options.RequireEap = False
VpnEntry.Options.RequirePap = True
VpnEntry.Options.RequireChap = True
VpnEntry.Options.RequireMSChap2 = True
VpnEntry.Options.RequireEncryptedPassword = False
VpnEntry.Options.UseLogOnCredentials = False
VpnEntry.Options.CacheCredentials = False
VpnEntry.DnsSuffix = "YYYYYYY.local"
VpnEntry.Options.UseDnsSuffixForRegistration = True
' *********** THE FOLLOWING LINE WILL CRASH ON WINDOWS 10 1803 **********
PhoneBook.Entries.Add(VpnEntry)
VpnEntry.UpdateCredentials(RasPreSharedKey.Client, PresharedKey)
If txt_Username.Text <> "" AndAlso txt_Password.Text <> "" Then
VpnEntry.UpdateCredentials(New Net.NetworkCredential(txt_Username.Text, txt_Password.Text), False)
VpnEntry.Options.CacheCredentials = True
VpnEntry.Update()
End If
PhoneBook.Dispose()
txt_Status.Text = VpnName & " successful added."
txt_Status.ForeColor = Color.DarkGreen
Catch ex As Exception
Console.WriteLine("Error while adding " & VpnName & "." & Environment.NewLine & ex.ToString)
Finally
End Try
End Sub
Can somebody help me?
I didn't found an updated DotRAS.dll.
Best would be a working example without external DLL.
Thank you in advance.

"Response received is incomplete"

So I reversed the syntax of this send sms code from c# to vb net so I can reuse it.
The code works sometimes, but for some reason it would often give me the "response received is incomplete" exception.
I was thinking perhaps my code is processing commands faster than my GSM device, could handle, so I tried increasing the timeout response for the serial port, still ends up with this exception.
What do you think is the problem and what would you recommend I do to solve it?
Public Class SmsHelper
Public receiveNow As AutoResetEvent
#Region "Open and Close Ports"
'Open Port
Public Function OpenPort(portName As String, baudRate As Integer, dataBits As Integer, readTimeout As Integer, writeTimeout As Integer) As SerialPort
receiveNow = New AutoResetEvent(False)
Dim port As New SerialPort()
Try
port.PortName = portName
'COM1
port.BaudRate = baudRate
'9600
port.DataBits = dataBits
'8
port.StopBits = StopBits.One
'1
port.Parity = Parity.None
'None
port.ReadTimeout = readTimeout
'300
port.WriteTimeout = writeTimeout
'300
port.Encoding = Encoding.GetEncoding("iso-8859-1")
port.NewLine = vbCrLf
AddHandler port.DataReceived, AddressOf port_DataReceived
port.Open()
port.DtrEnable = True
port.RtsEnable = True
Catch ex As Exception
Throw ex
End Try
Return port
End Function
' Send AT Command
Public Function SendATCommand(port As SerialPort, command As String, responseTimeout As Integer, errorMessage As String) As String
Try
port.DiscardOutBuffer()
port.DiscardInBuffer()
receiveNow.Reset()
port.Write(command & Convert.ToString(vbCrLf))
Dim input As String = ReadResponse(port, responseTimeout)
Console.WriteLine("Received data is " & input)
If (input.Length = 0) OrElse ((Not input.EndsWith(vbCr & vbLf & "> ")) AndAlso (Not input.EndsWith(vbCr & vbLf & "OK" & vbCr & vbLf))) Then
Throw New ApplicationException("No success message was received.")
End If
Return input
Catch ex As Exception
Throw ex
Finally
End Try
End Function
'Receive data from port
Public Sub port_DataReceived(sender As Object, e As SerialDataReceivedEventArgs)
Try
If e.EventType = SerialData.Chars Then
receiveNow.[Set]()
End If
Catch ex As Exception
Throw ex
End Try
End Sub
Public Function ReadResponse(port As SerialPort, timeout As Integer) As String
Dim serialPortData As String = ""
Try
Do
If receiveNow.WaitOne(timeout, False) Then
Dim data As String = port.ReadLine()
serialPortData += data
Else
'Console.WriteLine("SerialPortData data is " & serialPortData)
If serialPortData.Length > 0 Then
Console.WriteLine("SerialPortData is " & serialPortData.ToString)
Throw New ApplicationException("Response received is incomplete.")
Else
Throw New ApplicationException("No data received from phone.")
End If
End If
Loop While Not serialPortData.EndsWith(vbCr & vbLf & "OK" & vbCr & vbLf) AndAlso Not serialPortData.EndsWith(vbCr & vbLf & "> ") AndAlso Not serialPortData.EndsWith(vbCr & vbLf & "ERROR" & vbCr & vbLf)
Catch ex As Exception
Throw ex
End Try
Return serialPortData
End Function
Shared readNow As New AutoResetEvent(False)
Public Function SendMessage(port As SerialPort, phoneNo As String, message As String) As Boolean
Dim isSend As Boolean = False
Try
Dim recievedData As String = SendATCommand(port, "AT", 3000, "No phone connected")
Dim command As String = "AT+CMGF=1" + Char.ConvertFromUtf32(13)
recievedData = SendATCommand(port, command, 3000, "Failed to set message format.")
' AT Command Syntax - http://www.smssolutions.net/tutorials/gsm/sendsmsat/
command = (Convert.ToString("AT+CMGS=""") & phoneNo) + """" + Char.ConvertFromUtf32(13)
recievedData = SendATCommand(port, command, 3000, "Failed to accept phoneNo")
'wait(2)
command = message & Char.ConvertFromUtf32(26)
recievedData = SendATCommand(port, command, 3000, "Failed to send message")
Console.WriteLine("Received data is " & recievedData)
If recievedData.EndsWith(vbCr & vbLf & "OK" & vbCr & vbLf) Then
isSend = True
ElseIf recievedData.Contains("ERROR") Then
isSend = False
End If
Return isSend
Catch ex As Exception
Throw ex
End Try
End Function
Private Shared Sub DataReceived(sender As Object, e As SerialDataReceivedEventArgs)
Try
If e.EventType = SerialData.Chars Then
readNow.[Set]()
End If
Catch ex As Exception
Throw ex
End Try
End Sub
#End Region
End Class

Image location won't write to file and Image won't load from file location

well I want to make the program write a an image location to a text file, and then when the user presses the "load" button, it reads that image location and sets it as the Image of the PictureBox, but so far I have had no success at all.
Private Sub Btn_Save_Click(sender As Object, e As EventArgs) Handles Btn_Save.Click
Dim path As String = My.Computer.FileSystem.SpecialDirectories.MyPictures + "\Card Library\Configs\" + "config_card.aygo"
Dim path2 As String = My.Computer.FileSystem.SpecialDirectories.MyPictures + "\Card Library\Configs\" + "set_cardimg.aygo"
' Create or overwrite the file.
Dim fs As FileStream = File.Create(path)
Dim fs2 As FileStream = File.Create(path2)
' Add text to the file.
Dim info As Byte() =
New UTF8Encoding(True).GetBytes(
"----------Saved Card Settings----------" + vbNewLine +
"Level: " + My.Settings.Level.ToString + vbNewLine +
"NoMonster: " + My.Settings.NoMonster.ToString + vbNewLine +
"Spell: " + My.Settings.Spell.ToString + vbNewLine +
"Trap: " + My.Settings.Trap.ToString + vbNewLine +
"XYZLevel: " + My.Settings.XyzLevel.ToString + vbNewLine +
"ATKValue: " + My.Settings.ATKValue.ToString + vbNewLine +
"DEFValue: " + My.Settings.DEFValue.ToString + vbNewLine +
"AttributeID: " + My.Settings.AttributeID.ToString + vbNewLine +
"CardID: " + My.Settings.CardID.ToString)
fs.Write(info, 0, info.Length)
fs.Close()
Dim info2 As Byte() =
New UTF8Encoding(True).GetBytes(CardImage.InitialImage.ToString)
fs2.Write(info2, 0, info2.Length)
fs2.Close()
MsgBox("Configuration saved successfully!", vbInformation)
End Sub
Private Sub Btn_Load_Click(sender As Object, e As EventArgs) Handles Btn_Load.Click
Dim path As String = My.Computer.FileSystem.SpecialDirectories.MyPictures + "\Card Library\Configs\" + "config_card.aygo"
Try
My.Settings.Level = CInt(GetSettingItem(path, "level"))
My.Settings.NoMonster = CInt(GetSettingItem(path, "nomonster"))
My.Settings.Spell = CBool(GetSettingItem(path, "spell"))
My.Settings.Trap = CBool(GetSettingItem(path, "trap"))
If My.Settings.NoMonster = 1 Then
If My.Settings.Spell = True Then
CardFt.Card_Spell()
Else
If My.Settings.Trap = True Then
CardFt.Card_Trap()
Else
CardFt.Card_Legendary()
End If
End If
End If
My.Settings.XyzLevel = CInt(GetSettingItem(path, "xyzlevel"))
If My.Settings.XyzLevel = 1 Then
CardFt.Card_XYZ()
End If
My.Settings.ATKValue = GetSettingItem(path, "atkvalue")
ATKText.Text = GetSettingItem(path, "atkvalue")
My.Settings.DEFValue = GetSettingItem(path, "defvalue")
DEFText.Text = GetSettingItem(path, "defvalue")
My.Settings.AttributeID = CInt(GetSettingItem(path, "attributeid"))
If My.Settings.AttributeID = 1 Then
AttributeLayer.Image = My.Resources.Earth
ElseIf My.Settings.AttributeID = 2 Then
AttributeLayer.Image = My.Resources.Water
ElseIf My.Settings.AttributeID = 3 Then
AttributeLayer.Image = My.Resources.Fire
ElseIf My.Settings.AttributeID = 4 Then
AttributeLayer.Image = My.Resources.Wind
ElseIf My.Settings.AttributeID = 5 Then
AttributeLayer.Image = My.Resources.Dark
ElseIf My.Settings.AttributeID = 6 Then
AttributeLayer.Image = My.Resources.Light
ElseIf My.Settings.AttributeID = 7 Then
AttributeLayer.Image = My.Resources.Divine
End If
My.Settings.CardID = CInt(GetSettingItem(path, "cardid"))
CardFt.Card_Loader()
If My.Computer.FileSystem.FileExists(My.Computer.FileSystem.SpecialDirectories.MyPictures + "\Card Library\Configs\" + "set_cardimg.aygo") Then
Try
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText(My.Computer.FileSystem.SpecialDirectories.MyPictures + "\Card Library\Configs\" + "set_cardimg.aygo")
Catch ex As Exception : End Try
End If
Dim bitmap As New Bitmap(My.Computer.FileSystem.SpecialDirectories.MyPictures + "Card Library\Configs\" + "set_cardimg.aygo")
CardImage.Image = CType(bitmap, System.Drawing.Image)
Catch ex As Exception
MsgBox("An error occured while loading the configuration file: " & vbNewLine & ex.Message & vbNewLine & vbNewLine & ex.ToString, vbExclamation)
My.Computer.Clipboard.SetText(ex.ToString)
End Try
End Sub
The error that I get from this is:
System.ArgumentException: Parameter is not valid.
at System.Drawing.Bitmap..ctor(String filename)
at AnimeYuGiOhCardMaker.CardMaker.Btn_Load_Click(Object sender, EventArgs e) in C:\Users\Compusys\Documents\Visual Studio 2012\Projects\Anime Yu-Gi-Oh Card Maker\Anime Yu-Gi-Oh Card Maker\Form1.vb:line 521
Now then, when the Save Button is being pressed It does not write the image location to file however it writes the following:
System.Drawing.Bitmap
This is why I get the error above.
The actual error is from here:
Dim bitmap As New Bitmap(My.Computer.FileSystem.SpecialDirectories.MyPictures + "Card Library\Configs\" + "set_cardimg.aygo")
CardImage.Image = CType(bitmap, System.Drawing.Image)
The error occurs even with an actual file path.
I tried a few different ways but none of them worked. Any help would be really appreciated. Thanks.
--
Dom
The original question has changed several times, including the exception. The current state of the question has several problems, the main one being this:
If My.Computer.FileSystem.FileExists(My.Computer.FileSystem.SpecialDirectories.MyPictures + "\Card Library\Configs\" + "set_cardimg.aygo") Then
Try
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText(My.Computer.FileSystem.SpecialDirectories.MyPictures _
+ "\Card Library\Configs\" + "set_cardimg.aygo")
' EMPTY CATCH !!!!!!
Catch ex As Exception : End Try
End If
Dim bitmap As New Bitmap(My.Computer.FileSystem.SpecialDirectories.MyPictures _
+ "Card Library\Configs\" + "set_cardimg.aygo")
CardImage.Image = CType(bitmap, System.Drawing.Image)
set_cardimg.aygo is just a config file which contains some text. it is not a valid image file, so you cannot create a bitmap from it.
You should open that file, read the contents into a variable, then if it is a valid location, create the bitmap from it, or better just set the picturebox .Location and let it load the image without you creating a bitmap first.

thread pool not executing in service

Hi stackoverflow community...
I am a little stumped. I have written an application to control collect printing stats, each print job is managed by a new thread and as a console application the code works a treat. When I try initialize the same thread queue worker in a service, it does not run through the class it is meant to launch. This only happens on Windows 8 works stations.
Here are some code snippets.
Protected Overrides Sub OnStart(ByVal args() As String)
' Add code here to start your service. This method should set things
' in motion so your service can do its work.
Dim tmp As New pmon_Audit
objwriter.AutoFlush = True
tmp.StartAudit()
End Sub
Imports SpoolMonitor
Imports System.Printing
Imports System.Threading
Imports Amib.Threading
Imports System.Net.Sockets
Public Class pmon_Audit
Friend WithEvents pmon As New PrinterMonitorComponent
Public ThreadPool As New SmartThreadPool(10, 1000, 0)
Public Sub StartAudit()
pmon.MonitorJobAddedEvent = True
'' Add printer to monitor
Try
For Each p As PrinterInformation In New PrinterInformationCollection
Try
pmon.AddPrinter(p.PrinterName)
WriteLog(String.Format("Printer {0} added to monitor", p.PrinterName))
Catch ex As Exception
WriteLog(ex.ToString)
End Try
Next p
Catch ex As Exception
WriteLog(ex.ToString)
End Try
End Sub
''' <summary>
''' Event that gets fired each time a job is added
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
Private Sub pmon_jobAdded(ByVal sender As Object, ByVal e As PrintJobEventArgs) Handles pmon.JobAdded
Dim myPrintServer As New LocalPrintServer(PrintSystemDesiredAccess.AdministrateServer)
Try
Dim pq As PrintQueue = myPrintServer.GetPrintQueue(e.PrintJob.PrinterName)
Dim jobAdded As New pmon_JobAdded(e.PrintJob)
pq.GetJob(e.PrintJob.JobId).Pause()
WriteLog("JobID " + e.PrintJob.JobId.ToString + " is paused")
ThreadPool.QueueWorkItem(New Amib.Threading.Action(AddressOf jobAdded.run))
Catch ex As Exception
WriteLog(ex.ToString)
End Try
Public Function run()
Dim myPrintServer As New LocalPrintServer(PrintSystemDesiredAccess.AdministrateServer)
Dim pq As PrintQueue = myPrintServer.GetPrintQueue(pjReceived.PrinterName)
curPT = pq.CurrentJobSettings.CurrentPrintTicket
If jb Is Nothing Then
Throw New ArgumentNullException("printJobRecord", "printJobRecord is null.")
End If
Try
WriteLog("JobID " + pjReceived.JobId.ToString + " added to monitor")
jb.JobID = pjReceived.JobId
While pjReceived.Spooling
Thread.Sleep(800)
pjReceived.Update()
End While
Try
If pjReceived.Color = True Then
jb.Colour = 2
Else
jb.Colour = 0
End If
WriteLog("JobID " + pjReceived.JobId.ToString + " Colour = " + jb.Colour.ToString)
Catch ex As Exception
jb.Colour = 1
End Try
Try
jb.Account = pjReceived.UserName
WriteLog("JobID " + pjReceived.JobId.ToString + " Account = " + jb.Account)
Catch ex As Exception
jb.Account = "Admin"
End Try
Try
jb.Application = pjReceived.Document
WriteLog("JobID " + pjReceived.JobId.ToString + " Application = " + jb.Application)
Catch ex As Exception
WriteLog(ex.ToString)
End Try
Try
If pq.CurrentJobSettings.CurrentPrintTicket.CopyCount > pjReceived.Copies Then
jb.Copies = pq.CurrentJobSettings.CurrentPrintTicket.CopyCount
ElseIf pq.UserPrintTicket.CopyCount > pjReceived.Copies Then
jb.Copies = pq.UserPrintTicket.CopyCount
Else
jb.Copies = pjReceived.Copies
End If
WriteLog("JobID " + pjReceived.JobId.ToString + " Copies = " + jb.Copies.ToString)
Catch ex As Exception
jb.Copies = 1
End Try
Try
jb.DeviceName = pjReceived.PrinterName
WriteLog("JobID " + pjReceived.JobId.ToString + " PrinterName = " + jb.DeviceName)
Catch ex As Exception
End Try
Try
jb.DataType = pjReceived.DataType
Catch ex As Exception
End Try
Try
jb.Document = pjReceived.Document
WriteLog("JobID " + pjReceived.JobId.ToString + " Document = " + jb.Document)
Catch ex As Exception
jb.Document = "UNKNOWN"
End Try
Try
jb.Driver = pjReceived.DriverName
WriteLog("JobID " + pjReceived.JobId.ToString + " Driver = " + jb.Driver)
Catch ex As Exception
jb.Driver = "UNKOWN"
End Try
Try
If pq.CurrentJobSettings.CurrentPrintTicket.Duplexing > pq.UserPrintTicket.Duplexing Then
jb.Duplex = pq.CurrentJobSettings.CurrentPrintTicket.Duplexing
Else
jb.Duplex = pq.UserPrintTicket.Duplexing
End If
If jb.Duplex = "twoSided" Then
jb.Duplex = "1"
Else
jb.Duplex = "0"
End If
WriteLog("JobID " + pjReceived.JobId.ToString + " Duplex = " + jb.Duplex)
Catch ex As Exception
jb.Duplex = "0"
End Try
Try
jb.JobDate = pjReceived.Submitted
WriteLog("JobID " + pjReceived.JobId.ToString + " JobDate = " + jb.JobDate)
Catch ex As Exception
jb.JobDate = Date.Now
End Try
Try
jb.JobSize = pjReceived.JobSize
Catch ex As Exception
jb.JobSize = "0"
End Try
Try
jb.Location = Dns.GetHostName.ToUpper
WriteLog("JobID " + pjReceived.JobId.ToString + " Location = " + jb.Location)
Catch ex As Exception
jb.Location = "UNKOWN"
End Try
Try
jb.Media = pq.CurrentJobSettings.CurrentPrintTicket.PageMediaSize.PageMediaSizeName
jb.Media = pjReceived.PaperKind
WriteLog("JobID " + pjReceived.JobId.ToString + " Media = " + jb.Media)
Catch ex As Exception
jb.Media = "201"
End Try
Try
jb.NUP = pq.CurrentJobSettings.CurrentPrintTicket.PagesPerSheet
Catch ex As Exception
jb.NUP = 0
End Try
Try
jb.PageCount = pjReceived.TotalPages
WriteLog("JobID " + pjReceived.JobId.ToString + " PageCount = " + jb.PageCount.ToString)
Catch ex As Exception
jb.PageCount = 1
End Try
Try
jb.PortName = pq.QueuePort.Name
Catch ex As Exception
End Try
Try
myPrintServer.Dispose()
Catch ex As Exception
WriteLog(ex.ToString)
End Try
Catch ex As Exception
pq.GetJob(pjReceived.JobId).Resume()
myPrintServer.Dispose()
WriteLog(ex.ToString)
End Try
GC.Collect()
Return 0
End Function

If possible to cotinue a For Each loop after an error jump in VB.NET?

I have a BackGroundWorker with a For Each loop that is inside of a Try Catch and I need to detect the error and continue the For Each loop whit the next item.
Actually I have a list of data to send to a server trough UDP and wait for an ACK, but if the server didn't answer in 5 seconds the timeout error is cachet and the whole process is aborted.
I need to do something like this
Dim MyData_Array As String()
For Each MyData As String In MyData_Array
MyData_Actual = MyData
' Translate the passed message into ASCII and store it as a Byte array.
Dim data As [Byte]() = System.Text.Encoding.ASCII.GetBytes(MyData)
Dim RemoteIpEndPoint As New IPEndPoint(IPAddress.Any, 0)
If data.Length = 67 Then
XMyData += 1
Dim Tx As New UdpClient()
Tx.Connect(Host, Port)
Tx.Client.SendTimeout = 5000
Tx.Client.ReceiveTimeout = 5000
Tx.Send(data, data.Length)
data = Tx.Receive(RemoteIpEndPoint)
Tx.Close()
Else
MyData_ErrorList += MyData & vbCrLf
End If
'Report progress
Porcentaje = (XMyData * 100) / MyData_Array.Count
BackgroundWorker1.ReportProgress(Porcentaje, "Sending MyData " & XMyData.ToString & " de " & MyData_Array.Count.ToString & " : " & MyData)
If BackgroundWorker1.CancellationPending Then
e.Cancel = True
Exit For
End If
Next
End If
Catch ex As TimeoutException
MyData_ErrorList += MyData_Actual & vbCrLf
'**********************************************************
'Here need to delay 100mS and get back to the For Each to process the next item
'**********************************************************
Catch ex As Exception
MyData_List = ex.Message & vbCrLf & "StackTrace: " & ex.StackTrace & vbCrLf & MyData_List
End Try
Put the Try/Catch inside the for loop.
Dim MyData_Array As String()
For Each MyData As String In MyData_Array
Try
MyData_Actual = MyData
' Translate the passed message into ASCII and store it as a Byte array.
Dim data As [Byte]() = System.Text.Encoding.ASCII.GetBytes(MyData)
Dim RemoteIpEndPoint As New IPEndPoint(IPAddress.Any, 0)
If data.Length = 67 Then
XMyData += 1
Dim Tx As New UdpClient()
Tx.Connect(Host, Port)
Tx.Client.SendTimeout = 5000
Tx.Client.ReceiveTimeout = 5000
Tx.Send(data, data.Length)
data = Tx.Receive(RemoteIpEndPoint)
Tx.Close()
Else
MyData_ErrorList += MyData & vbCrLf
End If
'Report progress
Porcentaje = (XMyData * 100) / MyData_Array.Count
BackgroundWorker1.ReportProgress(Porcentaje, "Sending MyData " & XMyData.ToString & " de " & MyData_Array.Count.ToString & " : " & MyData)
If BackgroundWorker1.CancellationPending Then
e.Cancel = True
Exit For
End If
Catch ex As TimeoutException
MyData_ErrorList += MyData_Actual & vbCrLf
Catch ex As Exception
MyData_List = ex.Message & vbCrLf & "StackTrace: " & ex.StackTrace & vbCrLf & MyData_List
'If you want to exit the For loop on generic exceptions, uncomment the following line
'Exit For
End Try
Next
You might consider putting the try catch inside the for loop, if the iterative collection is not modified somehow by the error. Then handle the exception and continue the for loop.
How you have your loop and try/catch setup now will cause the entire loop to be broken out of on the timeout exception since the try/catch is placed outside the loop.
The your code would look more like this:
For Each MyData As String In MyData_Array
Try
'Perform code for each loop iteration
Catch ex As TimeoutException
'Handle Exception Here
End Try
Next