5 Replies - 540 Views - Last Post: 13 October 2017 - 06:36 PM Rate Topic: -----

#1 ChrisKays  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 29-September 17

Update Listview status using multithreading/ThreadPool

Posted 29 September 2017 - 02:11 AM

Hi,

I've been pulling my hair for days now,
I have a list view with multiple column and one of the column is a status that i nee to manipulate as i connect to a device using TCP/IP.
My list view contains a list of device each with an IP address and i have a button Connect that will establish the connection to the device but the problem is that the connection process takes long therfore i would like to create a different thread that will go through every selected device and as it executing i want to show something like (Connecting...) in the status row and once the connection is established successfully i want to show (Connected) or if it fails the show(Connection failed)

i'v create two separate thread to handle this but obviously this not the right way, i would like to use Threadpool to do this,
anyone can help?

 Private ListView_Sync_Conn_Start_Thread As Threading.Thread
 Private ListView_Sync_Operation_Thread As Threading.Thread

 Private Sub StartSyncConnection()
        ListView_Sync_Conn_Start_Thread = New System.Threading.Thread(AddressOf ReaderConnectThread)
        ListView_Sync_Conn_Start_Thread.IsBackground = True
        ListView_Sync_Conn_Start_Thread.Start()
    End Sub

    Private Sub StartSyncOperationConnection()
        ListView_Sync_Operation_Thread = New System.Threading.Thread(AddressOf ReaderSyncOperationThread)
        ListView_Sync_Operation_Thread.IsBackground = True
        ListView_Sync_Operation_Thread.Start()
    End Sub

    Private Sub ReaderConnectThread()
        Try
            Invoke(New SyncStartedDelegate(AddressOf SyncConnStarted))
        Catch ex As Exception
        End Try
    End Sub

    Private Sub ReaderSyncOperationThread()
        Try
            Invoke(New ReaderOperationDeletgate(AddressOf ReaderSyncOperation))
        Catch ex As Exception
        End Try
    End Sub

    Private Delegate Sub SyncStartedDelegate()
    Private Sub SyncConnStarted()
        btnConnect.Enabled = False
        btnConnect.Text = "Connecting..."
        btnAdd.Enabled = False
        btnEdit.Enabled = False
        btnDelete.Enabled = False
        btnSync.Enabled = False
        For Each lItem As ListViewItem In lvItems.SelectedItems
            lItem.SubItems(StatusColumn.Index).Text = "Connecting..."
        Next
    End Sub

    Private Delegate Sub ReaderOperationDeletgate()
    Private Sub ReaderSyncOperation()

        Dim objBioReader As New PDConnect.clsBiometricReader()
        Cursor = Cursors.WaitCursor

        For Each lItem As ListViewItem In lvItems.SelectedItems
            objBioReader = CType(lItem.Tag, PDConnect.clsBiometricReader)
            BioReaderNumber = objBioReader.GetReaderID(objBioReader.IP_Address, myDataFunctions)

            IsConnected = BiometricFunction.ConnectReader(objBioReader.IP_Address, Convert.ToInt32(objBioReader.POrt_Number))

            If IsConnected = True Then
                btnConnect.Text = "Disconnect"
                btnConnect.Refresh()
                lItem.SubItems(StatusColumn.Index).Text = "Connected"

                btnConnect.Enabled = True
                btnConnect.Text = "Disconnect"
                btnAdd.Enabled = True
                btnEdit.Enabled = True
                btnDelete.Enabled = True
                btnSync.Enabled = True
            Else
                MessageBox.Show("Unable to connect " + objBioReader.Name + " - " + BiometricFunction.GetErrorCode, "Connection Failed", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
                lItem.SubItems(StatusColumn.Index).Text = "Disconnect"
                btnConnect.Text = "Disconnect"
            End If
        Next
        Cursor = Cursors.Default

    End Sub



Is This A Good Question/Topic? 0
  • +

Replies To: Update Listview status using multithreading/ThreadPool

#2 IronRazer  Icon User is offline

  • Custom Control Freak
  • member icon

Reputation: 1444
  • View blog
  • Posts: 3,674
  • Joined: 01-February 13

Re: Update Listview status using multithreading/ThreadPool

Posted 29 September 2017 - 07:51 PM

Have you considered using the Task Class to do this?

By creating an Action(Of T) Delegate and passing it to the first parameter of the TaskFactory.StartNew Method (Action(Of Object), Object) along with each selected ListViewItem by using a loop, you could accomplish this.

The connection status of each selected item would be updated in real time as each connection succeeds/fails. This would all be done in separate threads so that your gui thread is not froze up while each connection is being made.

Below is a simple example that may help. It is close to what you are trying to do except, it is just Pinging some addresses and updating the 2nd column of my listview with the Ping result instead of a device's connection status.

You can test it in a new Form project with 1 Button and 1 ListView added to the form. Name the Button as "Button_Connect" and name the ListView as "ListView_Connections". I did not comment the code in the Load event as it is only setting up the ListView properties, columns, and adding some items to it for this example.
Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        With ListView_Connections
            .View = View.Details
            .FullRowSelect = True
            .HeaderStyle = ColumnHeaderStyle.Nonclickable
            .HideSelection = False

            .Columns.Add("Column_Ip", "Ip Address", 150)
            .Columns.Add("Column_Status", "Status", 120)

            Dim IpAddresses() As String = {"198.01.01.06", "www.jojogo12345.com", "www.google.com", "198.01.01.00", "www.yahoo.com", "bad_address_throws_exception"}
            For Each ipa As String In IpAddresses
                Dim lvi As ListViewItem = ListView_Connections.Items.Add(ipa)
                lvi.SubItems.Add("--------------")
            Next
        End With
    End Sub

    Private Sub Button_Connect_Click(sender As Object, e As EventArgs) Handles Button_Connect.Click

        'Here i create an Action(Of Object) delegate that encapsulates a sub with one parameter. This is the parameter which the ListViewItem is passed to.
        Dim CheckIp As Action(Of Object) = (Sub(objLvItem As Object)
                                                Dim lvi As ListViewItem = CType(objLvItem, ListViewItem) 'cast the Object parameter to a ListViewItem
                                                Dim ip As String = lvi.SubItems(0).Text.Trim 'gets the ip address from the subitem
                                                Dim bconn As Boolean = False

                                                Try
                                                    bconn = My.Computer.Network.Ping(ip, 10000) 'try pinging the ip address in a Try/Catch
                                                Catch ex As Exception
                                                    'perhaps you might want to write the exception message to a Log or notify user of bad ip?
                                                End Try

                                                'invoke a sub in the thread of the window that the ListView is on, which updates the 'status' subitem
                                                ListView_Connections.Invoke(Sub()
                                                                                lvi.SubItems(1).Text = If(bconn, "Connected", "Failed...")
                                                                            End Sub)

                                            End Sub)

        'Now iterate through the Selected Items of the ListView
        For Each itm As ListViewItem In ListView_Connections.SelectedItems
            itm.SubItems(1).Text = "Connecting..." 'update the 'status' subitem to indicate the connection is in progress
            Task.Factory.StartNew(CheckIp, itm) 'create and start a new Task to check the ip of this ListViewItem
        Next

    End Sub
End Class



Posted Image

I am sure you would need to do a little reading and experimenting to implement this to your exact needs but, i hope it gives you a direction to go in.
Was This Post Helpful? 1
  • +
  • -

#3 andrewsw  Icon User is offline

  • the case is sol-ved
  • member icon

Reputation: 6375
  • View blog
  • Posts: 25,756
  • Joined: 12-December 12

Re: Update Listview status using multithreading/ThreadPool

Posted 01 October 2017 - 11:12 PM

@OP You do not need to quote the large previous post, there is a Reply button further down the page, or a Fast Reply box.
Was This Post Helpful? 0
  • +
  • -

#4 ChrisKays  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 29-September 17

Re: Update Listview status using multithreading/ThreadPool

Posted 01 October 2017 - 11:13 PM

Thank you Razor,

this is exactly what i'v been looking for, you a life saver
Was This Post Helpful? 0
  • +
  • -

#5 KC10513  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 13-October 17

Re: Update Listview status using multithreading/ThreadPool

Posted 13 October 2017 - 01:11 AM

Hi there,

this topic is one of the thing i'v been looking for but due to factors outside of my control, I must use .NET 2.0, which prevents me using Task<T>, so I have to refactor this code somehow.

How can I achieve the same result, without using TaskFactory.StartNew Method (Action(Of Object), Object) as this function is not available on the 2.0 framework.
Any idea would be highly appreciated.

Thanks in advance
Was This Post Helpful? 0
  • +
  • -

#6 IronRazer  Icon User is offline

  • Custom Control Freak
  • member icon

Reputation: 1444
  • View blog
  • Posts: 3,674
  • Joined: 01-February 13

Re: Update Listview status using multithreading/ThreadPool

Posted 13 October 2017 - 06:36 PM

KC10513,
You should ask your questions by creating your own question thread.

Until then, i will give you this info to get you started. Use the ThreadPool Class, particularly this ThreadPool.QueueUserWorkItem Method if you need to pass an argument in as i do with the ListViewItems in the example i gave above.

There are examples and lots of info about using a ThreadPool in the links i gave above. With a quick google search for "ThreadPool vb.net", it will bring up a lot more info and examples you can check out.

If you have trouble, you can create a new question thread. Post a link back to this thread if you believe it will help others to understand. 8)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1