[Last Call] Learn about multicloud storage options and how to improve your company's cloud strategy. Register Now

x
?
Solved

vb.net and background worker for system uptime

Posted on 2014-12-08
11
Medium Priority
?
367 Views
Last Modified: 2014-12-09
I am attempting to write a small amount of code to return to me the system uptime of a remote workstation.  It works when ran directly from a button, but when i try to put it in a background thread it fails everytime.

Below is the code i am using:

Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
        Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
        Try
            Dim str_ServerName As String = TextBox1.Text
            Dim pc As New PerformanceCounter("System", "System Up Time", "", str_ServerName)
            pc.NextValue()
            Dim ts As TimeSpan = TimeSpan.FromSeconds(pc.NextValue)
            MsgBox(str_ServerName & " has been up for " & ts.Days & " days, " & ts.Hours & " hours, " & ts.Minutes & " minutes, " & " and " & ts.Seconds & " seconds.", , "System Uptime")
        Catch ex As Exception
            MsgBox("Workstation Uptime not found", MsgBoxStyle.Information, "Information")
        End Try
    End Sub

    Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged

    End Sub

    Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
        If e.Cancelled = True Then
        End If
    End Sub

Open in new window


I declare the below:
Private bw As BackgroundWorker = New BackgroundWorker
    Public Sub New()
        InitializeComponent()
        bw.WorkerReportsProgress = True
        bw.WorkerSupportsCancellation = True
        AddHandler bw.DoWork, AddressOf BackgroundWorker1_DoWork
        AddHandler bw.ProgressChanged, AddressOf BackgroundWorker1_ProgressChanged
        AddHandler bw.RunWorkerCompleted, AddressOf BackgroundWorker1_RunWorkerCompleted
    End Sub

Open in new window


I then try to run the method from a button:
  If Not bw.IsBusy = True Then
            bw.RunWorkerAsync()
        End If

Open in new window


What am i doing wrong?
0
Comment
Question by:derek7467
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
11 Comments
 
LVL 45

Expert Comment

by:AndyAinscow
ID: 40487474
The background worker doesn't support UI - eg. MessageBox - elements.  You would need to pass the uptime back to the main thread to display the result.
0
 

Author Comment

by:derek7467
ID: 40487476
This is the error i get:

Cross-thread operation not valid: Control 'TextBox1' accessed from a thread other than the thread it was created on.
0
 

Author Comment

by:derek7467
ID: 40487478
How do i pass it back?
0
NEW Veeam Agent for Microsoft Windows

Backup and recover physical and cloud-based servers and workstations, as well as endpoint devices that belong to remote users. Avoid downtime and data loss quickly and easily for Windows-based physical or public cloud-based workloads!

 

Author Comment

by:derek7467
ID: 40487492
I supposed this would be bad coding to use the below???

TextBox.CheckForIllegalCrossThreadCalls = false
0
 
LVL 41

Expert Comment

by:Kyle Abrahams
ID: 40487519
Use a BeginInvoke to bubble it up to the UI thread:
http://msdn.microsoft.com/en-us/library/a06c0dc2(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1
Me.BeginInvoke(new Delegate(AddressOf showMsgBox),  str_ServerName & " has been up for " & ts.Days & " days, " & ts.Hours & " hours, " & ts.Minutes & " minutes, " & " and " & ts.Seconds & " seconds.", "System Uptime")

public sub showMessageBox(text as string, Caption as string)
 MsgBox(text, , Caption)
end sub

Open in new window

0
 
LVL 1

Expert Comment

by:Michael O'Shea
ID: 40487522
Hi, I suggest all will become clear when you Google "InvokeRequired"
0
 
LVL 86

Accepted Solution

by:
Mike Tomlinson earned 2000 total points
ID: 40487875
First, pass the Computer Name to RunWorkerAsync():
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If Not bw.IsBusy = True Then
            bw.RunWorkerAsync(TextBox1.Text)
        End If
    End Sub

Open in new window


Then you can grab it in DoWork() with "e.Argument".  Set "e.Result" to your output:
    Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
        Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
        Try
            Dim str_ServerName As String = e.Argument.ToString
            Dim pc As New PerformanceCounter("System", "System Up Time", "", str_ServerName)
            pc.NextValue()
            Dim ts As TimeSpan = TimeSpan.FromSeconds(pc.NextValue)
            e.Result = str_ServerName & " has been up for " & ts.Days & " days, " & ts.Hours & " hours, " & ts.Minutes & " minutes, " & " and " & ts.Seconds & " seconds."
        Catch ex As Exception
            e.Result = "Workstation Uptime not found"
        End Try
    End Sub

Open in new window


Finally, grab "e.Result" in the RunWorkerCompleted() event:
    Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
        Dim result As String = e.Result
        MessageBox.Show(result)
    End Sub

Open in new window

0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 40488071
I agree with Mike:  The BW supports passing data back to the UI via its established events. There is no need for CheckForIllegalCrossThreadCalls, BeginInvoke, or InvokeRequired as the others have mentioned.
0
 
LVL 45

Expert Comment

by:AndyAinscow
ID: 40488223
From the help files about the BackgroundWorker:
http://msdn.microsoft.com/en-us/library/cc221403%28v=vs.95%29.aspx

To pass data back to the calling process, set the Result property of the DoWorkEventArgs object that is passed to the event handler. This value can be read when the RunWorkerCompleted event is raised at the end of the operation.
0
 

Author Closing Comment

by:derek7467
ID: 40488792
thank you
0
 
LVL 45

Expert Comment

by:AndyAinscow
ID: 40488875
ps.
Reading the help files could result in a quicker answer than just asking a question and waiting.
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Please read the paragraph below before following the instructions in the video — there are important caveats in the paragraph that I did not mention in the video. If your PaperPort 12 or PaperPort 14 is failing to start, or crashing, or hanging, …
In a question here at Experts Exchange (https://www.experts-exchange.com/questions/29062564/Adobe-acrobat-reader-DC.html), a member asked how to create a signature in Adobe Acrobat Reader DC (the free Reader product, not the paid, full Acrobat produ…

650 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question