Internet.com - The Network for Technology Professionals * >IT Professionals o IT Management o Security o Storage o Server o Networking o Small Business o Communications o Enterprise Applications o Database o Mobile o Hardware o IT News * > Developers o Architect o Java / OS o Microsoft Technology o Web Development * >Solutions o HotList o Video * eBook Library * Webopedia * >Login o Manage My Profile * >Register o Why Join? advertisement Not sure if you have an account? Include Code Search Tips TODAY'S HEADLINES | ARTICLE ARCHIVE | SKILLBUILDING | TIP BANK | SOURCEBANK | FORUMS | NEWSLETTERS Browse DevX PHP for Windows Showcase Azure Services Platform Center MSDN Spotlight RIA Developement Center Free IBM developerWorks Downloads, Tutorials and Articles on DevX eBook Library for Technology Professionals Jupiterweb Webcasts DevX: .NET Zone .NET Technical Discussion Group CoDe Magazine VB2theMax Archive MSDN Spotlight RIA Development Center Visual Studio 2010 Showcase DevX: Java Zone Java Boutique Java Discussion Forum Sourcebank RIA Development Center Free IBM developerWorks Downloads, Tutorials and Articles on DevX DevX: C++ Zone C++ Discussion Forum Sourcebank PHP for Windows Showcase MSDN Spotlight DevX: Web Development Zone DevX: Project Cool Web Development Discussion Forum AJAX Forum RIA Development Center Free IBM developerWorks Downloads, Tutorials and Articles on DevX DevX: Architecture Zone Architect and Design Forum DevX: Database Dev Zone Database Discussion Forum Free IBM developerWorks Downloads, Tutorials and Articles on DevX DevX: Security Zone Security Discussion Forum DevX: Open Source Zone Free IBM developerWorks Downloads, Tutorials and Articles on DevX DevX: XML Zone XML Discussion Forum DevX: Semantic Zone DevX: Visual Basic Zone freeVBcode Home Page VB Classic Discussion Forum VB2theMax Archive DevX: ASP Zone ASP.NET Discussion Forum DevX: Enterprise Zone Architect and Design Forum Visual Studio 2010 Showcase DevX: Wireless Zone Wireless Discussion Forum RIA Development Center Move to the Future with Multicore Code C++0x: The Dawning of a New Standard Going Mobile: Getting Your Apps On the Road Software as a Service: Building On-Demand Applications in the Cloud A New Era for Rich Internet Applications The Road to Ruby Vista's Bounty: Surprising Features Take You Beyond .NET 3.0 The AJAX Framework Roundup Special Report: Virtual Machines Usher In a New Era Java/.NET Interop: Bridging Muddled Waters Wireless Special Report: Marching Toward Mobility Home Page for Special Report: Ensuring Successful Web Services Today and Tomorrow Special Report: Winning with Web Services How to Create a Disaster Recovery Plan Special Report: Judging Java Past C/C++ 10-Minute Solutions Past Java 10-Minute Solutions Past DHTML 10-Minute Solutions Past SQL Server 10-Minute Solutions Past Oracle 10-Minute Solutions Past DB2 10-Minute Solutions Past Visual Basic 10-Minute Solutions Past XML 10-Minute Solutions Shop DevX APIfinder.com Specialized Dev Zones Vendor Solutions eBook Library NEW Webcasts .NET Java C++ Web Dev Architecture Database Security Open Source XML Semantic Web VB Classic ASP/ASP.NET Enterprise Mobile Special Reports 10-Minute Solutions DevXtra Editors' Blog Shop DevX APIfinder Get Help with Visual Basic Past Visual Basic 10-Minute Solutions DevX: Visual Basic Zone More VB Articles There have been several solutions to multithreading and creating responsive user interfaces. Tell us some of the methods you have found in VB6 or your experiences with multithreading in VB.NET. Partners & Affiliates Data Centers Televisions Website Hosting Run Enterprise Java Run Cloud Apps Boat Donations PDA Phones & Cases Desktop Computers Calling Cards prepaid phone card Data Center Business Email prepaid calling card Java App Server advertisement advertisement Resources advertisement IBM DB2 e-kit for Database Professionals. Extending database skills is fast and easy with new features and this e-kit. Learn how and start taking advantage of easier DB2 administration features today. Add Multithreading to Your VB.NET ApplicationsAverage Rating: 4.4/5 | Rate this item | 128 users have rated this item. * Email Article * Print Article * Comment on this Article * Share Article o Digg o del.icio.us o Newvine o furl o StumbleUpon o BlinkList o Newsvine o Magnolia o Facebook o Tailrank o Slashdot o Technorati o Google Bookmarks o Yahoo Favorites o Windows Live o Ask Add Multithreading to Your VB.NET Applications (cont'd) Passing Data Through Multithreaded Procedures The last example shows a rather simple situation. Multithreading has many complications that you have to work out when you program. One issue that you will run into is passing data to and from the procedure passed to the constructor of the Thread class. That is to say, the procedure you want to kick off on another thread cannot be passed any parameters and you cannot return data from that procedure. This is because the procedure you pass to the thread constructor cannot have any parameters or return value. To get around this, wrap your procedure in a class where the parameters to the method are written as fields of the class. advertisement A simple example of this would be if we had a procedure that calculated the square of a number: Function Square(ByVal Value As Double) As Double Return Value * Value End Function To make this procedure available to be used in a new thread we would wrap it in a class: Public Class SquareClass Public Value As Double Public Square As Double Public Sub CalcSquare() Square = Value * Value End Sub End Class Use this code to start the CalcSquare procedure on a new thread. following code: Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim oSquare As New SquareClass() t = New Thread(AddressOf oSquare.CalcSquare) oSquare.Value = 30 t.Start() End Sub Notice that after the thread is started, we do not inspect the square value of the class, because it is not guaranteed to have executed once you call the start method of the thread. There are a few ways to retrieve values back from another thread. The easiest way is to raise an event when the thread is complete. We will examine another method in the next section on thread synchronization. The following code adds the event declarations to the SquareClass. Public Class SquareClass Public Value As Double Public Square As Double Public Event ThreadComplete(ByVal Square As Double) Public Sub CalcSquare() Square = Value * Value RaiseEvent ThreadComplete(Square) End Sub End Class Catching the events in the calling code has not changed much from VB6, you still declare the variables WithEvents and handle the event in a procedure. The part that has changed is that you declare that a procedure handles the event using the Handles keyword and not through the naming convention of Object_Event as in VB6. Dim WithEvents oSquare As SquareClass Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click oSquare = New SquareClass() t = New Thread(AddressOf oSquare.CalcSquare) oSquare.Value = 30 t.Start() End Sub Sub SquareEventHandler(ByVal Square As Double) _ Handles oSquare.ThreadComplete MsgBox("The square is " & Square) End Sub The one thing to note with this method is that the procedure handling the event, in this case SquareEventHandler, will run within the thread that raised the event. It does not run within the thread from which the form is executing. Previous Page: Keep It Under Control Next Page: Synchronizing the Threads Page 1: Working with Threads Page 3: Passing Data Through Multithreaded Procedures Page 2: Keep It Under Control Page 4: Synchronizing the Threads * Email Article * Print Article * Comment on this Article * Share Article o Digg o del.icio.us o Newvine o furl o StumbleUpon o BlinkList o Newsvine o Magnolia o Facebook o Tailrank o Slashdot o Technorati o Google Bookmarks o Yahoo Favorites o Windows Live o Ask Please rate this item (5=best) 1 2 3 4 5 By dghervas March 13 2010 8:07 PM PDT i want to disable or enable a control that doesent suport invoke method (from a diferent thread offcourse) how would i do that? A timer to be more specific. If i do it as i would normaly do "timer1.enabled = true" it doesent give any error but doesent work either. I would apreciate some help, thanks Reply to this comment By erwinyn@gmail.com January 9 2010 6:30 PM PDT End Class Class ThreadProc Delegate Sub UpdateTextCallBack(ByVal ctrl As TextBox, ByVal msg As Int32) Dim ctrl As TextBox Dim msg As Int32 Public t As Thread ' create 3 thread for handle 3 counter Public Sub StartCounter(ByVal ctrl As TextBox, ByVal msg As Int32) Me.ctrl = ctrl: Me.msg = msg t = New Thread(AddressOf Counter) t.Start() End Sub ' counter procedure Public Sub Counter() Try While True UpdateTextControl(ctrl, msg) msg = msg 1 Thread.Sleep(100) ' delay counter in mili second If msg > 100 Then msg = 0 End While Catch at As ThreadAbortException MessageBox.Show(at.Message) ' message: thread was being aborted End Try End Sub ' update TextBox value used Invoke metode (thread-safe) Public Sub UpdateTextControl(ByVal ctrl As TextBox, ByVal msg As Int32) If ctrl.InvokeRequired Then ctrl.Invoke(New UpdateTextCallBack(AddressOf UpdateTextControl), New Object() {ctrl, msg}) Else ctrl.Text = msg.ToString End if End Sub End Class ' ..FINISH Reply to this comment By erwinyn January 9 2010 6:23 PM PDT Imports System Imports System.Net Imports System.Windows Imports System.Threading ' add 3 TextBox and 2 Button on your form then run this sample (used vb2008) Public Class Form1 ' for save object in array list Private threadList As ArrayList = ArrayList.Synchronized(New ArrayList) ' running 3 counter with 3 thread Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim out() As TextBox = {TextBox1, TextBox2, TextBox3} For i As Int32 = 0 To 2 Dim obj As New ThreadProc obj.StartCounter(out(i), 0) threadList.Add(obj) Next End Sub ' stop all counter Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click For i As Int32 = 0 To threadList.Count - 1 Dim x As ThreadProc = TryCast(threadList(i), ThreadProc) If x IsNot Nothing Then If x.t.ThreadState ThreadState.Aborted Then x.t.Abort() End If End If Next End Sub ' (continue) Reply to this comment By LyndonL January 7 2010 6:59 PM PDT It may be worth mentioning that that sub BackgroundProcess will be created in a new thread, which differs from the thread that Form1 (where the Listbox resides) was created. you cannot directly manipulate items created in different threads. Workaround: Use Delegate/Invoke method: After Form1 Class insert: Delegate Sub listbox1Delegate(ByVal str As String) At bottom of class insert: Private Sub Setlistbox1(ByVal str As String) If listbox1.InvokeRequired Then listbox1.Invoke(New listbox1Delegate(AddressOf Setlistbox1), str) Else listbox1.items.add = str End If End Sub Then, inplace of the ListBox1.Items.Add("Iterations: " i) in the BackgroundProcess sub, change it to: setlistbox1("Iterations: " i) Reply to this comment By tqnga December 15 2009 3:48 AM PDT Hello I have a problem when using Thread: Public Class ConvertThread Public SourceTable as DataTable Public iRowCount as integer=0 Public Sub PerformConvert() SyncLock GetType(ConvertToUnicode) For Each oRow As DataRow In SourceTable.Rows iRowCount = 1 'I want thread'll be stopped when iRowCount=SourceTable.Rows.Count Next End SyncLock End Class Call thread: For Each oTable As DataTable In sourceDataset.Tables Dim oConvert As New ConvertThread Dim oThread As New Threading.Thread(AddressOf oConvert.PerformConvert) oConvert .SourceTable = oTable oThread.Start() If oConvert.iRowCount = oTable.Rows.Count Then oThread.Abort() oTable.AcceptChanges() End If Next But I get exception "Collection was modified; enumeration operation may not execute." when using this code. And I think this code don't help me manage threads which I declare. Pls help me. Thank you very much! Reply to this comment By Ramana December 6 2009 1:57 AM PDT I'm created one service, check by below code. Threading not working properly, Protected Overrides Sub OnStart(ByVal args() As String) Try t = New System.Timers.Timer(TimerInterval) '10 secs AddHandler t.Elapsed, AddressOf TimerFired With t .AutoReset = True .Enabled = True .Start() End With Catch ex As Exception writeErrorToFile(ErrorLogFileName, ex.ToString) End Try End Sub Private Sub TimerFired(ByVal sender As Object, ByVal e As ElapsedEventArgs) Try 'currently there are 3 processes CheckQueueToNotify() 'to display desktop notification CheckQueueToProcess("Local") ' to process queues in local database CheckQueueToProcessServer() ' to process queues in server database Catch ex As Exception writeErrorToFile(ErrorLogFileName, ex.ToString) End Try End Sub The three functions not running properly, when i'm debug the focus goto first function and suddenly focus move off and run second function. totally weired. pls giv me suggestion. Reply to this comment By dusky September 28 2009 3:49 PM PDT thanks for creating a easy to understand guide ^^ Most other guides ive read on multi threading are all over the place and i couldnt figure out how to do it. Got it first time with this 1 tho =) Reply to this comment By Steve September 21 2009 4:16 AM PDT When I posted my previous comments I had only read the first page of this article. On reading the rest I realize that the whole article is very bad. It presents examples that just won't work and shows that the author does not really understand multi-threading of Windows Forms. You can not safely call a Windows Forms object (a control) from within a thread that did not create it. Any attempts to do so at best won't work and at worst may corrupt data within your program. My suggested solution is the correct way to proceed, but this article should be removed or re-written because its advice is very misleading. Reply to this comment By Jasbir Singh September 7 2009 3:07 AM PDT when i run the above code, i got this error, "Cross-thread operation not valid: Control 'ListBox1' accessed from a thread other than the thread it was created on." Reply to this comment Reply by Steve September 21 2009 2:49 AM PDT I don't agree with the advice given by Vijayaragavan. Just ignoring illegal cross-thread calls is a recipe for problems. The correct way is to check whether the call is a cross-thread call and then if necessary marshall the call back onto the main thread using the "Invoke" method. I find the easiest way is first to define a function that adds an item to the listbox: Private Sub ListAdd(ByVal S as String) ListBox1.Items.Add(S) End Sub Then create a delegate for it. Delegates are just a technique to allow a function to be passed as a parameter to another function: Private Delegate Sub ListAddDelegate(ByVal S As String) Now from within your thread you can do this: If ListBox1.InvokeRequired Then ListBox1.Invoke(New ListAddDelegate(AddressOf ListAdd), New Object() {"Item to add"}) Else ListAdd("Item to add") End If The "New Object(){}" part creates an array of objects to match the parameters of the Delegate. In this case there is only one parameter, but we still need to make it into an array. "InvokeRequired" tests to see if this is a cross-thread call. If it's not we just call the function directly. Reply by Vijayaragavan September 10 2009 3:43 AM PDT Hi Use this code start of that function where you are trying to access the listbox CheckForIllegalCrossThreadCalls = False or create a another thread and there update the listbox control By manson August 11 2009 12:46 PM PDT hi, i think this post is great!, but i have a questions about. I need this source and i'm thinking to put it into web page (aspx), what happen if users close my web page... , can i abort my thread? wich event i must use? Reply to this comment By Art May 25 2009 12:15 AM PDT hi, fist... this is the best tutorial, but a have a one question: Sub SquareEventHandler(ByVal Square As Double) _ Handles oSquare.ThreadComplete MsgBox("The square is " & Square) <-- This works textbox1.Text = Square <-- this does not work End Sub what is the problem ? sorry for my poor english :( Reply to this comment Reply by erwinyn January 9 2010 5:40 PM PDT 'For art: Imports System.Threading '.......................................................................... Public Class Form1 Dim WithEvents oSquare As SquareClass Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click oSquare = New SquareClass Dim t As New Thread(AddressOf oSquare.CalcSquare) oSquare.Value = 30 t.Start() End Sub Private Sub oSquare_ThreadComplete(ByVal Square As Double) Handles oSquare.ThreadComplete MsgBox("The square is " & Square) End Sub End Class '.......................................................................... Public Class SquareClass Public Value As Double Public Square As Double Public Event ThreadComplete(ByVal Square As Double) Public Sub CalcSquare() SyncLock GetType(SquareClass) Square = Value * Value End SyncLock RaiseEvent ThreadComplete(Square) End Sub End Class Reply by Steve September 21 2009 3:08 AM PDT Windows forms are generally not thread-safe. The difference in your example is that the message box has been created by your thread so it is no problem for your thread to use it, but the textbox is on a form created by your main thread and cannot be accessed legally from another thread. For a solution see my other post to Jasbir Singh. Because all the controls on a form are (normally) created on the main thread, the invoked function (ListAdd in my example) can update as many other controls on the same form as you wish, rather than needing to make a separate invoke call for each. Comments (cont.) Page 1 Add a comment Enter a username Email address (used only for verification; it will not be displayed or added to any list) Please type the alphanumeric characters above. What's this? I cannot read this. Please generate a New image Your comment: (Maximum characters: 1200). You have characters left. HTML characters will not be displayed. I agree to the Terms of Use Need help? Acceptable Use Policy Intel Atom Developer Program: Get Everything You Need to Create and Sell Breakthrough Netbook Apps HP PartnerONE | SolutionsINFINITE Visit us at hp.com/partners/us Win amazing prizes for creating groundbreaking netbook apps in the Intel® Atom™ Developer Challenge! Best Practices for Developing a Web Site: Checklists, Tips & Strategies. Download Exclusive eBook Now. Guide to Developing a Web Site: Best Practices, Tips and Strategies. Download Exclusive eBook Now. advertisement Advertising Info | Permissions | Help | Site Map | Network Map | About Internet.com The Network for Technology Professionals Search: About Internet.com Copyright 2010 QuinStreet Inc. All Rights Reserved. Legal Notices, Licensing, Permissions, Privacy Policy. Advertise | Newsletters | E-mail Offers Solutions Whitepapers and eBooks Helpful Cloud Computing Resources Article: An Introduction to Hyper-V Virtualization Microsoft PDF: Fact-Based Comparison of Hosted Services: Google vs. Microsoft MORE WHITEPAPERS, EBOOKS, AND ARTICLES Webcasts Ensuring Performance Meets Business and Web User Needs MORE WEBCASTS, PODCASTS, AND VIDEOS Downloads and eKits HP PartnerONE | SolutionsINFINITE MORE DOWNLOADS, EKITS, AND FREE TRIALS Tutorials and Demos Guide: Recommendations for Implementing Cloud Security Article: Explore Application Lifecycle Management Tools in Visual Studio 2010 Internet.com Hot List: Get the Inside Scoop on IT and Developer Products New Security Solutions Using Intel(R) vPro(TM) Technology All About Botnets MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES