logo
down
shadow

Change UI from another class created in a thread in vb.net


Change UI from another class created in a thread in vb.net

By : Havilah Communicatio
Date : November 22 2020, 02:59 PM
I wish this help you This is the most common problem for people who are just starting to understand multi threading. Think about how WinForm controls interact with calling elements. They use events to signal to the outside world that something happened within them. You can do the same:
code :
Public Class SomeForm
    Private connectionsList As New List(Of RemoteEnd)

    Public Property Port As Integer

    Sub FindComputers()
        For Each comp As String In APINetworkItems.GetAllComputersInDomain
            For Each addr As IPAddress In Dns.GetHostEntry(comp).AddressList.Where(Function(a) a.AddressFamily = AddressFamily.InterNetwork)
                Dim remote As New RemoteEnd
                ' Add a handler to handle the Connected event that the RemoteEnd class exposes, and then call its Connect sub.
                ' Note that we do not add the instance to the list yet, as it's not really connected yet (not as long as the RemoteEnd class
                ' hasn't raised the Connected event...)
                AddHandler remote.Connected, AddressOf RemoteEnd_Connected
                remote.Connect(New IPEndPoint(addr, Port), addr, comp)
            Next
        Next
    End Sub

    Private Sub RemoteEnd_Connected(ByVal sender As Object, ByVal e As EventArgs)
        ' When the form catches the event, it restores the reference to the instance that raised it, and
        ' add the instance to the list. Keep in mind that the event will be handled on the same thread it was raised!
        ' That means that if you want to display data in a form control, you need to invoke the form to make the change!
        ' Here we just add a reference to a list, so it doesn't matter.
        Dim remote = DirectCast(sender, RemoteEnd)
        connectionsList.Add(remote)
        DoSomething(remote)
    End Sub

    Private Sub DoSomething(ByVal remote As RemoteEnd)
        ' ...
    End Sub
End Class


Public Class RemoteEnd
    Public Event Connected(ByVal sender As Object, ByVal e As EventArgs)

    Public Sub Connect(ByVal EndPoint As IPEndPoint, ByVal IP As IPAddress, ByVal Name As String)
        ' To work efficiently, when this sub is called we need to start the asynchronous process and return immediately.
        ' When the connection is fully handled, we will raise the event and carry a reference to this instance to the form.
        ' Because QueueUserWorkItem only takes in one state object to pass parameters, we create a single object that
        ' contains all the information needed to connect and pass that.
        Dim params = New ConnectionInfo(EndPoint, IP, Name)
        ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf HandleConnectionAsync), params)
    End Sub

    Private Sub HandleConnectionAsync(ByVal connectionInfos As ConnectionInfo)
        ' ...

        ' Here we raise the Connected event for the outside world, carrying a reference to this instance,
        ' and possibly an instance derived from EventArgs. Here we return nothing.
        RaiseEvent Connected(Me, Nothing)
    End Sub
End Class


Public Class ConnectionInfo
    Public Property EndPoint As IPEndPoint
    Public Property IP As IPAddress
    Public Property Name As String

    Public Sub New(ByVal _ep As IPEndPoint, ByVal _ip As IPAddress, ByVal _name As String)
        EndPoint = _ep
        IP = _ip
        Name = _name
    End Sub
End Class
Private Delegate Sub SetTextDelegate(ByRef ctrl As Control, ByVal text As String)

Private delSetText As New SetTextDelegate(AddressOf SetText)

Private Sub SetText(ByRef ctrl As Control, ByVal text As String)
    ctrl.Text = text
End Sub

Private Sub DoSomething()
    If Me.InvokeRequired Then
        Me.Invoke(delSetText, {SomeTextBox, "This is the text to set..."})
    Else
        SomeTextBox.Text = "This is the text to set..."
    End If
End Sub


Share : facebook icon twitter icon
The thread created with newSingleThreadExecutor a newly created thread or a deamon thread?

The thread created with newSingleThreadExecutor a newly created thread or a deamon thread?


By : Duvadesa
Date : March 29 2020, 07:55 AM
may help you . The documentation of newSingleThreadExecutor() specifies that it is (almost) the same as using newFixedThreadPool(1), so each call to that method will create an executor with its own thread. That thread will not be a daemon thread by default, but you could change that by providing your own ThreadFactory that produces daemon threads.
Calling a method from the class that created a thread, in the thread

Calling a method from the class that created a thread, in the thread


By : Oscar Santos
Date : March 29 2020, 07:55 AM
wish of those help What about creating ClassTwo constructer that gets a parameter with CallingClass type?
code :
public class ThreadClass extends Thread{
    CallingClass callingClass;

    public ThreadClass(CallingClass callingClass) {
            this.callingClass = callingClass;
    }
    public void run(){
        //Some thread logic
        callingClass.someMethod();
    }
}
public class CallingClass{
    CallingClass(){
        ClassTwo thread = new ClassTwo(this);
        thread.start();
    }

    public void someMethod(){}

}
Control 'progressBar1' accessed from a thread other than the thread it was created on in my business class

Control 'progressBar1' accessed from a thread other than the thread it was created on in my business class


By : Spark-Exp-17
Date : March 29 2020, 07:55 AM
Hope this helps Your problem is that your control exists on thread A but you are trying to access it via thread B. This is a 'no-no'. Try the following code
code :
private void btnSend_Click(object sender, EventArgs e)
{
    Task.Run(() => LoadData(System.Threading.SynchronizationContext.Current, progressBar1));
}

private void LoadData (System.Threading.SynchronizationContext synchContext, ProgressBar1ObjectType progressBar)
{
    string filePath = tbPath.Text;
    ETLBusiness etlBusiness = new ETLBusiness(filePath);

    synchContext.Post(state => etlBusiness.LoadData(progressBar), null);
}
Thread _myThread = null;
private void btnSend_Click(object sender, EventArgs e)
{
    SynchronizationContext synchContext = SynchronizationContext.Current;
    _myThread = new Thread(() => LoadData(synchContext, progressBar1));

    myThread.Start();

}

private void LoadData (System.Threading.SynchronizationContext synchContext, ProgressBar1ObjectType progressBar)
{
    string filePath = tbPath.Text;
    ETLBusiness etlBusiness = new ETLBusiness(filePath);

    synchContext.Post(state => etlBusiness.LoadData(progressBar), null);
    _myThread.Abort();
}
If threads only can access static methods to a class with its own instance, created by a different thread, what thread w

If threads only can access static methods to a class with its own instance, created by a different thread, what thread w


By : Varalakshmi
Date : March 29 2020, 07:55 AM
Hope that helps Ok, there's a lot of misinformation in your post.
1)Services and Runnables do not, by default, have their own thread. Services run on the UI thread, although they can create a thread (an IntentService will do so by default). Runnables run on whatever thread calls run on them. But unless you post them to a Handler attached to another thread or to a Thread object, they won't start a new one.
C++ will thread created in class share the same class variable?

C++ will thread created in class share the same class variable?


By : SB_711
Date : March 29 2020, 07:55 AM
like below fixes the issue All threads will see the same queue. That's the beauty of concurrent programming. (You can use thread_local storage duration if you want a different instance per thread - this is a new addition to C++ since C++11.)
Normally, you need to make sure the relevant members are used in a thread-safe manner. Atomic types (std::atomic from C++11) and mutual exclusion units (std::mutex from C++11) are used for that.
Related Posts Related Posts :
  • Multithreading on multiple datatables
  • How can get array random from another array string?
  • Is there a way to do something similar to IIF(condition, trueValue, falseValue) within a linq statement?
  • Simple VB.Net text base communication server
  • Visual Basic add to timestamp date
  • Catch event from Main Form
  • Hangman Game: How To Make The Program Know I Wrote The Correct Word?
  • [UWP]Resize, compress and get base64 string from BitmapImage
  • Vb.net Get the text from Textbox inserted line by line in other Textboxes
  • VB Adding an item to listbox on a different form giving null reference exception
  • Retaining the selected radio button in Visual Basic
  • How to display which file is playing by Media Player from Playlist in vb.net ?
  • Dragging controls during runtime - how to lock controls
  • Error : Table Insertion returns error in vb.net and msacess
  • Debugging error: "Object reference not set to an instance of an object"
  • is there a cleaner method of handling textbox validating events
  • How to Subtract/Add 3 or more Date Time variables
  • Moveable PictureBox transparent over PictureBox
  • Button outputs infinite times
  • me.control.remove is removing every second control in a loop for some reason
  • Is there a time when Exception can be nothing?
  • How do I store persistent user preferences in VB.net
  • Adding NETWORK SERVICE as new user to AD LDS instance administrator member
  • More efficient error catching?
  • Add thread loop timer
  • VB textbox.enter gives null value (accumulator)
  • FedEx WSDL help on ASP.NET (VB) Web App
  • Snakes and ladders Vb.net
  • How to get hidden files and folders name and show it in a listbox control
  • SQLite in vb 2010
  • How to find total size of files in ReadOnlyCollection(Of String)
  • Bind a detail report to a class model with properties stored in a Dictionary (VB.NET, Devexpress)
  • SQL queries to Excel sheets - can't pass the first query
  • Dataview filtering vb.net
  • Scrollable with the mouse
  • Nested If - ElseIf - Select Case
  • Getting what comes after a certain string - Visual Basic
  • Mvvm. Textbox never change with System.Threading.Thread.Sleep
  • How to add items from a MenuStrip event to a ListBox using a For Next Loop
  • unlinking comboboxes from each other
  • Calling a DLL from Visual Studio VB 2015
  • Finding a specific value in a file
  • Mouse Events in vb.net
  • How do you programmatically check a checkbox column in a datagridview? vb.net
  • shadow
    Privacy Policy - Terms - Contact Us © animezone.co