-
Jul 25th, 2012, 01:23 PM
#41
Re: Understanding Multi-Threading in VB.Net
The SynchronizationContext is used to submit methods to run on the thread associated with the context.
In your case, the SynchronizationContext object belongs to the UI thread therefore whenever a method is executing on any other thread and needs to run a method back on the UI thread, it uses the SynchronizationContext's Send to do so.
-
Jul 25th, 2012, 01:47 PM
#42
New Member
Re: Understanding Multi-Threading in VB.Net
Sorry, but it's a bit hard write in english because it's the first time I do it in a forum, and this is a difficult argument
I used your ThreadExtensions Class, and now i need to call some subs in RemoteClient classes, which are created in the BackgroundWorker thread, from the UI Thread....(from button click event subs and others). How can I do this?
-
Jul 25th, 2012, 02:12 PM
#43
Re: Understanding Multi-Threading in VB.Net
Well classes in the strictest sense aren't really thread specific, running methods are. That means a single class can have many different methods running at the same time on different threads. You can call the class' methods from the UI thread as you call any method. The only problem with this is when your method intends to interact with an object that another method running on another thread is interacting with. In that case you would need to consider some kind of synchronization so that the two threads don't try to access the object at exactly the same time. If such a condition doesn't exist then you can safely call the method from the UI in the normal way.
The only reason we even need a SynchronizationContext with multi-threaded objects is because controls are a special case and need to be manipulated on the thread they were created on(usually the UI thread). When controls aren't involve things become much simpler.
Last edited by Niya; Jul 25th, 2012 at 02:15 PM.
-
Jul 25th, 2012, 03:11 PM
#44
New Member
Re: Understanding Multi-Threading in VB.Net
This is exactly what I want...
Code:
In that case you would need to consider some kind of synchronization so that the two threads don't try to access the object at exactly the same time.
How can I do this? I have to call some subs in my RemoteClient class which permits my application to send text to the clients... I call this subs from both threads (UI thread adn BackgroundWorker thread) and It could happen the two threads try to access the sub and the objects used in the sub, at exactly the same time....
-
Jul 25th, 2012, 05:21 PM
#45
Re: Understanding Multi-Threading in VB.Net
Well calling the same method multiple times from different threads isn't actually a problem. Running methods are really instances of the methods. What you need to look out for are lines of code that access objects outside the scope of the methods for example a private field.
Consider the following:-
vbnet Code:
Public Class Test Public Sub Method1() For i = 1 To 100 Debug.Print(i) Next End Sub End Class
You are free to call Method1 as many times as you want from as many threads as you want. If you called it from one thread the same time another thread calls it, then there would be two different instances of the same method running. There is no danger with this. However, imagine this:-
vbnet Code:
Public Class Test Private lstNumbers As New List(Of Integer) Public Sub Method2() For i = 1 To 100 lstNumbers.Add(CStr(lstNumbers.Count)) Next End Sub End Class
Now there is a real problem when calling the above Method2 more than once from different threads. This is because these different instances of the running Method2 would be accessing the same list and there is a danger both threads access the list at the same time. The solution would be to synchronize access to the list like this:-
vbnet Code:
Public Class Test Private lstNumbers As New List(Of Integer) Public Sub Method2() For i = 1 To 100 SyncLock lstNumbers lstNumbers.Add(CStr(lstNumbers.Count)) End SyncLock Next End Sub End Class
SyncLock would block if it was called on the same object, in this case lstNumbers, on another thread. When that other thread passes its End SyncLock then the blocked thread would be allowed to proceed and other calls to SyncLock on lstNumbers from other threads would be blocked in the same manner until it reaches its End SyncLock.
Last edited by Niya; Jul 25th, 2012 at 05:28 PM.
-
Jul 26th, 2012, 12:38 PM
#46
New Member
Re: Understanding Multi-Threading in VB.Net
You're the best vb.net programmer I've never seen... How can I say a big thank you?? Thanks to you I managed to fix issues that plagued me for months!!
-
Jul 27th, 2012, 11:55 AM
#47
Re: Understanding Multi-Threading in VB.Net
Oh its no problem my friend
-
Sep 26th, 2012, 01:02 PM
#48
New Member
Re: Understanding Multi-Threading in VB.Net
Hi!
First of all, thanks for the great tutorial, it's been very very instructive.
And now the question, what would be the procedure to use two buttons and two labels that do the same thing, or in my application they would need both differnt inputs from my I/O system? (I'm quite a newbie to this so maybe it's a stuipid question)
Thanks !
-
Sep 26th, 2012, 02:34 PM
#49
Re: Understanding Multi-Threading in VB.Net
Tell me more about what you want to do with the I/O system.
-
Sep 27th, 2012, 07:53 AM
#50
New Member
Re: Understanding Multi-Threading in VB.Net
Basicly I want to read inputs from it ("start"), next I would activate outputs to activate relays and put tension on my testprobe, next would be to test the output of the testprobe with analog input channels.
-
Sep 27th, 2012, 11:47 AM
#51
Re: Understanding Multi-Threading in VB.Net
Ok, I don't really know too much about relays and test probes but if I understand correctly, these things you speak are I/O devices and you want to process input on one thread and output on another....is this correct ?
-
Sep 27th, 2012, 02:33 PM
#52
New Member
Re: Understanding Multi-Threading in VB.Net
No, I want to use two or more threads that execute the same code but use differnt inputs/outputs, thats why I would need more than one variable in those threads, for example:
if input(nc) = 1 then
activate output0(nc)
end if
Thread number one would use input 0 and thread number two would use input 8, trough the nc variable, same with the output.
Maybe I'm just talking weird, sorry if I am
-
Sep 27th, 2012, 06:40 PM
#53
Re: Understanding Multi-Threading in VB.Net
Oh I see, the real problem is that you want to run the same method on different threads with different parameters. Well in the most basic cases you don't have to do anything special, you can just call the same method more than once each time on a different thread. However, if there is some kind of interaction between them or they are accessing the same resource then we have to cater to it.
Now, what approach are you taking to want to take with this. In this thread I show two forms of doing straight threaded coding. The first one where I show how to simply execute methods from a Form on different thread and the second way was to make a class with asynchronous methods and events that are raised on the UI thread. Which way are you thinking of ?
-
Sep 28th, 2012, 01:14 AM
#54
New Member
Re: Understanding Multi-Threading in VB.Net
I would need the second way is that I would need 2 variables for each thread, the number of thread (nc in the example above) and it's "place", since I've been teached to make a process that's secuencial with select case, each thread would be in another step of the process. For example, the fist thread is still on case number 10 and the second thread on case number 35. Is there some other way to make the same thing but easier?
And to not complicate things much, yes, they access the same resource, I'm thinking of making some sort of buffer to execute them.
Thanks
-
Sep 28th, 2012, 01:37 AM
#55
Re: Understanding Multi-Threading in VB.Net
Ok....I think I kinda get what you're saying now....lets see what you have so far and how we can thread it.
-
Sep 29th, 2012, 05:56 AM
#56
New Member
Re: Understanding Multi-Threading in VB.Net
For now I got the following:
Public Class Counter
Private context As Threading.SynchronizationContext = Threading.SynchronizationContext.Current
Public Event CountChanged As EventHandler(Of CountChangedEventArgs)
Protected Overridable Sub OnCountChanged(ByVal e As CountChangedEventArgs)
RaiseEvent CountChanged(Me, e)
End Sub
Public Sub CountAsync(ByVal paso As Integer)
ThreadExtensions.QueueUserWorkItem(New Func(Of Integer, String)(AddressOf Count), paso)
End Sub
Public Sub CountAsync2(ByVal paso As Integer)
ThreadExtensions.QueueUserWorkItem(New Func(Of Integer, String)(AddressOf Count), paso)
End Sub
Public Function Count(ByVal paso As Integer) As String
' Dim startTime As DateTime = DateTime.Now
Dim e As CountChangedEventArgs
For i = 0 To paso
e = New CountChangedEventArgs(i, paso)
Select Case i
Case 0
If context Is Nothing Then
OnCountChanged(e)
Else
ThreadExtensions.ScSend(context, New Action(Of CountChangedEventArgs)(AddressOf OnCountChanged), e)
End If
Threading.Thread.Sleep(2000)
Case 2
If context Is Nothing Then
OnCountChanged(e)
Else
ThreadExtensions.ScSend(context, New Action(Of CountChangedEventArgs)(AddressOf OnCountChanged), e)
End If
Threading.Thread.Sleep(200)
End Select
Next
' Return "Count took : " + (DateTime.Now - startTime).ToString
End Function
End Class
Public Class CountChangedEventArgs
Inherits EventArgs
Private _NumeroThread As Integer
Private _Paso As Integer
Public Sub New(ByVal nc As Integer, ByVal paso As Integer)
_NumeroThread = nc
_Paso = paso
End Sub
Public ReadOnly Property NumeroThread() As Integer
Get
Return _NumeroThread
End Get
End Property
Public ReadOnly Property Paso() As Integer
Get
Return _Paso
End Get
End Property
End Class
Public Class ThreadExtensions
Private args() As Object
Private DelegateToInvoke As [Delegate]
Public Shared Function QueueUserWorkItem(ByVal method As [Delegate], ByVal ParamArray args() As Object) As Boolean
Return Threading.ThreadPool.QueueUserWorkItem(AddressOf ProperDelegate, New ThreadExtensions With {.args = args, .DelegateToInvoke = method})
End Function
Public Shared Sub ScSend(ByVal sc As Threading.SynchronizationContext, ByVal del As [Delegate], ByVal ParamArray args() As Object)
sc.Send(New Threading.SendOrPostCallback(AddressOf ProperDelegate), New ThreadExtensions With {.args = args, .DelegateToInvoke = del})
End Sub
Private Shared Sub ProperDelegate(ByVal state As Object)
Dim sd As ThreadExtensions = DirectCast(state, ThreadExtensions)
sd.DelegateToInvoke.DynamicInvoke(sd.args)
End Sub
End Class
Public Class Form1
Private WithEvents m_cn As New Counter
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
m_cn.CountAsync(20)
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
m_cn.CountAsync2(30)
End Sub
Private Sub m_cn_CountChanged(ByVal sender As Object, ByVal e As CountChangedEventArgs) Handles m_cn.CountChanged
Label1.Text = CStr(e.NumeroThread)
Label2.Text = CStr(e.NumeroThread)
End Sub
End Class
I have no idea how to do the same thing with two threads. Thanks in advance !
-
Oct 1st, 2012, 04:51 PM
#57
Re: Understanding Multi-Threading in VB.Net
Why do you have two asynchronous Count methods ? You do realize you can have one and call it as many times as you want right ? And each one will execute on a separate thread. I don't really see much of a problem here. You have to remember that an executing method is actually an executing instance of a method.
-
Oct 13th, 2012, 08:19 PM
#58
New Member
Re: Understanding Multi-Threading in VB.Net
Hi,
I have a question. The following Sub from your tutorial takes an address of the Count function with the 'String' as the return type.
Code:
Public Sub CountAsync(ByVal Max As Integer)
ThreadExtensions.QueueUserWorkItem(New Func(Of Integer, String)(AddressOf Count), Max)
End Sub
My question is, is there anyway I can change the code so that it would work with Subs instead of Functions. Since my Connect Sub does not return anything, I don't need it to be a Function ? So, what I mean is the following:
Code:
Public Sub ConnectAsync(ByVal IP As String, ByVal Port As Integer)
ThreadExtensions.QueueUserWorkItem(New Func(Of String, Integer)(AddressOf Connect), IP, Port)
End Sub
Public Sub Connect(ByVal IP As String, Port As Integer)
'Some code here
End Sub
I have tried something like 'New Sub()' but that obviously did not work.
Thank you
Last edited by SNiiP3R; Oct 13th, 2012 at 08:27 PM.
-
Oct 13th, 2012, 08:52 PM
#59
New Member
Re: Understanding Multi-Threading in VB.Net
Okay, I figured it out. Please ignore my previous post.
Apparently, when we're dealing with Subs that don't return anything we have to use New Action(). So the above Sub would look something like this,
Code:
Public Sub ConnectAsync(ByVal IP As String, ByVal Port As Integer)
ThreadExtensions.QueueUserWorkItem(New Action(Of String, Integer)(AddressOf Connect), IP, Port)
End Sub
I'm still however, not too sure what to do with Subs that have no parameters ? For example,
Code:
Public Sub Disconnect()
ThreadExtensions.QueueUserWorkItem()
End Sub
Private Sub sockDisconnect()
End Sub
New Action() in this case is not working for some reason.
Last edited by SNiiP3R; Oct 13th, 2012 at 09:18 PM.
-
Oct 13th, 2012, 10:59 PM
#60
Re: Understanding Multi-Threading in VB.Net
Use the non generic Action delegate type.
vbnet Code:
'
Public Sub Disconnect()
ThreadExtensions.QueueUserWorkItem(New Action(AddressOf sockDisconnect))
End Sub
Last edited by Niya; Oct 13th, 2012 at 11:05 PM.
-
Nov 24th, 2012, 05:31 AM
#61
New Member
Re: Understanding Multi-Threading in VB.Net
Niya, I really have to say, by far this is the-best breakdown I have ever seen of multithreading for vb.net. I was having so much issues trying to figure this out for my self. You put this in plain,easy to follow language. I am forever great-full! As you can see it is 5:30AM and I have not been to sleep and I felt the need to register for the forums just to tell you this, thank you very much.
-
Nov 25th, 2012, 11:53 AM
#62
Re: Understanding Multi-Threading in VB.Net
Thank you friend....I'm glad it helped you
I thought it might be helpful to try and explain it in the way I would have liked someone to explain it to me when I didn't know how to do it. I seemed to have hit the mark Thx
Last edited by Niya; Nov 25th, 2012 at 12:12 PM.
-
Feb 6th, 2013, 10:25 PM
#63
New Member
Re: Understanding Multi-Threading in VB.Net
Niya, Thank you for providing these examples. I don't know if your still following this thread (as the last post was almost 4 months ago). However in case you are, would you be so kind as to provide an identical example of your count program without utilizing your ThreadExtensions routine. I'm using VB2005 and it will not resolve some of the 'With' instructions you used in the routine. And please don't tell me to upgrade, there are reasons why I'm using VB2005 and .net framework 2.0, which I won't discuss as it is off topic. Threading is a something I haven't had a need to code until now - so I'm new at it. Any help would be appreciated.
What I'm trying to do is to create a second thread that runs continuously in an endless loop. The code in the loop will read about a dozen Boolean values set from the UI thread, and send them out through the serial port to another device (PLC), then turn around and read some other data back from the serial port. Once the data is read back, it is unpacked and then checked to see if any values have changed since the last read. If so, I want to raise a 'status change' event on the UI thread and pass to the event what changed (which class instance) and the new property value (which can be set from either thread). After raising the event (if necessary), the thread will loop back to the beginning and start the communications again (a monitor program). The UI thread will respond to the event and update the screen accordingly. I have the communications part working. I'm trying to work out the threading - your count program pretty much has the functions I need - only I'm unable to use parts of the ThreadExtensions routine as they will not resolve in VB2005. How else can I do this?
Thanks.
-
Feb 7th, 2013, 04:52 AM
#64
Re: Understanding Multi-Threading in VB.Net
Use this one:-
vbnet Code:
Public Class ThreadExtensions
Private args() As Object
Private DelegateToInvoke As [Delegate]
Private Sub New(ByVal delegateArgs As Object(), ByVal delegateInstance As [Delegate])
Me.args = delegateArgs
Me.DelegateToInvoke = delegateInstance
End Sub
Public Shared Function QueueUserWorkItem(ByVal method As [Delegate], ByVal ParamArray args() As Object) As Boolean
Return Threading.ThreadPool.QueueUserWorkItem(AddressOf ProperDelegate, New ThreadExtensions(args, method))
End Function
Public Shared Sub ScSend(ByVal sc As Threading.SynchronizationContext, ByVal del As [Delegate], ByVal ParamArray args() As Object)
sc.Send(New Threading.SendOrPostCallback(AddressOf ProperDelegate), New ThreadExtensions(args, del))
End Sub
Private Shared Sub ProperDelegate(ByVal state As Object)
Dim sd As ThreadExtensions = DirectCast(state, ThreadExtensions)
sd.DelegateToInvoke.DynamicInvoke(sd.args)
End Sub
End Class
-
Feb 8th, 2013, 08:01 PM
#65
New Member
Re: Understanding Multi-Threading in VB.Net
Thanks a bunch Niya. That works perfectly in VB2005.
Dale
-
Mar 5th, 2013, 01:25 PM
#66
Registered User
Re: Understanding Multi-Threading in VB.Net
Hi Niya.
i have a small question! Can help me.
example: i have a url: (http://mangafox.me/manga/kingdom_hea...04/c030/1.html). And i wana get comic pictures in this page. Specifically, Downloading 3-4 or more pages in same time to speed up load.
only way I solved my problem.
-
Mar 5th, 2013, 11:11 PM
#67
Re: Understanding Multi-Threading in VB.Net
In the section where I show how to do multi-threaded classes, I made a class that executed the count on a non-UI thread. In your case you would have a your download method instead of a count. You simply instantiate multiple classes to perform multiple downloads.
-
Mar 6th, 2013, 08:04 AM
#68
Registered User
Re: Understanding Multi-Threading in VB.Net
-
May 27th, 2013, 11:50 AM
#69
New Member
Re: Understanding Multi-Threading in VB.Net
Hello Niya. Thanks for writing the article. I'm a beginner in VB so I could pickup first 2-3 posts and messed up afterwards.
Actually I have a list of files in my program and need to download 2 files simultaneously and on the completion of a file, it start downloading next in the list. and I'm just confused what to do and how to alter the code..
Will you help me please..
-
May 27th, 2013, 03:30 PM
#70
Re: Understanding Multi-Threading in VB.Net
Does your problem have to do with multi-threading it or downloading the files ? Have you already got the downloading part working ?
-
May 27th, 2013, 04:45 PM
#71
New Member
Re: Understanding Multi-Threading in VB.Net
downloading all files in a listbox one by one is not an issue, I used for next loop and it did the job. And also I like to mention that I used:
My.Computer.Network.Download()
I may use Webclient Download Method but thats not an issue at the moment. Multithreading is the issue..
-
May 27th, 2013, 05:51 PM
#72
Re: Understanding Multi-Threading in VB.Net
Show me the code you're using to download the files.
-
May 29th, 2013, 12:41 AM
#73
New Member
Re: Understanding Multi-Threading in VB.Net
here it is:
Code:
Dim Dir As String = InputBox("Directory", "Dir")
For i As Integer = 0 To lstLinks.Items.Count - 1
Dim targetFile As String = lstLinks.Items(i).ToString
Dim destFile As String
destFile = "E:\Downloads\" & Dir & "\" & i & ".jpg"
Try
My.Computer.Network.DownloadFile(targetFile, destFile, "", "", True, 10000, True, FileIO.UICancelOption.DoNothing)
Catch ex As Exception
tbStatus.Text += vbNewLine & "ERROR: File: " & i & " ERR Number: " & Err.Number & ". Description: " & Err.Description & "File Name: " & targetFile
End Try
Next
-
May 29th, 2013, 01:41 AM
#74
Re: Understanding Multi-Threading in VB.Net
I'm going to assume you're using VS2010 and later.
The simplest way to achieve what you want would be to put the downloading part in its own sub like this:-
vbnet Code:
'
Private Sub StartDownloads(ByVal Dir As String)
For i As Integer = 0 To lstLinks.Items.Count - 1
Dim targetFile As String = lstLinks.Items(i).ToString
Dim destFile As String
destFile = "E:\Downloads\" & Dir & "\" & i & ".jpg"
Try
My.Computer.Network.DownloadFile(targetFile, destFile, "", "", True, 10000, True, FileIO.UICancelOption.DoNothing)
Catch ex As Exception
tbStatus.Invoke(Sub()
tbStatus.Text += vbNewLine & "ERROR: File: " & i & " ERR Number: " & Err.Number & ". Description: " & Err.Description & "File Name: " & targetFile
End Sub)
End Try
Next
End Sub
And call it like:-
vbnet Code:
'
Dim Dir As String = InputBox("Directory", "Dir")
'Runs StartDownloads on a thread pool thread
Threading.ThreadPool.QueueUserWorkItem(Sub() StartDownloads(Dir))
Now this is really a simple scenario. It doesn't account for progress or knowing when the downloads are finished but its the most straightforward way if you don't require any of the complexities of a more robust file download system.
-
Jul 19th, 2013, 05:51 AM
#75
Lively Member
Re: Understanding Multi-Threading in VB.Net
Hello Niya, First of all Thanks for this delicious article. After reading your articles and reply here, I couldn't stop to ask.
I want to ask How can we pass multiple arguments on a thread.
Now As you have mentioned before that Thread.Start can accept only one parameter.. But why i am still asking because,
I have a Procedure which loads a .Txt file on a Listview.. in this function I pass .Txt file path and a Listview name.
Here I am not sure about how many times this procedure will be called. (It depends on number of .Txt files of a directory)
In other words, the procedure loads all the .Txt files of a directory on listviews.
Now my Query is, How to use ThreadPool to load all the .Txt files together. I mean instead of calling procedure one by one , how can i call this procedure to load the next .Txt file while the previous .Txt file is being loaded on the listview?
Here are the sample of codes i am talking about, Please have a look:
Code:
Public Sub LoadDB(ByVal bFile As String, ByVal LvName As ListView)
Try
Dim inputstream As New IO.StreamReader(bFile)
Dim newstr(5) As String
Dim ttt As String
Do While inputstream.Peek <> -1
Application.DoEvents()
ttt = inputstream.ReadLine().Trim
newstr = Split(ttt, vbtab)
With LvName.Items.Add(newstr(0).ToUpper)
.SubItems.Add(newstr(1).ToUpper)
.SubItems.Add(newstr(2).ToUpper)
.SubItems.Add(newstr(3).ToUpper)
.SubItems.Add(newstr(4).ToUpper)
End With
Loop
inputstream.Close()
Catch
End Try
End Sub
And Normally I am calling it like :
Code:
For i = 1 to numberOftxtFiles
LoadDB(fileDirpath & i.ToString, LvPhH1)
LoadDB(fileDirpath & i.ToString, LvPhH2)
Next i
Even I am calling it like..
Code:
For i = 1 to numberOftxtFiles
Threading.ThreadPool.QueueUserWorkItem(Sub() LoadDB(fileDirpath & i.ToString, LvPhH1))
Threading.ThreadPool.QueueUserWorkItem(Sub() LoadDB(fileDirpath & i.ToString, LvPhH2))
Next i
But it's not working...
Thanks
Regards,
Last edited by green.pitch; Jul 19th, 2013 at 06:00 AM.
-
Jul 19th, 2013, 06:07 AM
#76
Lively Member
Re: Understanding Multi-Threading in VB.Net
Sorry for dual posting.... Above code was not working due to Cross thread Problem..
Now after
CheckForIllegalCrossThreadCalls = False
it is working... Is it good to Disable CheckForIllegalCrossThreadCalls?
-
Jul 19th, 2013, 06:25 AM
#77
Re: Understanding Multi-Threading in VB.Net
Originally Posted by green.pitch
Is it good to Disable CheckForIllegalCrossThreadCalls?
NO NO NO NO NO! Don't do that at all. You're begging for disasters in the future. I dedicated an entire paragraph towards explaining why you cannot call change control properties from a non-UI thread. I showed at least two ways to properly interact with controls from worker threads. One way by use the Invoke property of controls or by use of a SynchronizationContext object. I strongly suggest you go back and read those particulars again. You should NEVER EVER set CheckForIllegalCrossThreadCalls to False.
-
Jul 20th, 2013, 01:01 AM
#78
Lively Member
Re: Understanding Multi-Threading in VB.Net
Ok thanks Niya, I tried to invoke a control on another project... But i am getting error. Please have a look to the following code.
Code:
Private Sub LoadFrm(ByVal pIDD As String, ByVal pMsg As String)
memFrmNum = memFrmNum + 1
FrmObj(memFrmNum) = New Form2
If FrmObj(memFrmNum).InvokeRequired Then
FrmObj(memFrmNum).Invoke(New Action(Of String)(AddressOf LoadFrm), pIDD)
FrmObj(memFrmNum).Invoke(New Action(Of String)(AddressOf LoadFrm), pMsg)
Else
FrmObj(memFrmNum).TextBox1.Text = pIDD
FrmObj(memFrmNum).Label1.Text = pMsg
End If
FrmObj(memFrmNum).Show()
End Sub
In above code I'm trying to load a form multiple times. Getting error on 'AddressOf LoadFrm'.
Please check the attachment.
ErrorOninvoke.zip
Regards,
-
Jul 20th, 2013, 03:04 AM
#79
Re: Understanding Multi-Threading in VB.Net
Originally Posted by green.pitch
Ok thanks Niya, I tried to invoke a control on another project... But i am getting error. Please have a look to the following code.
Code:
Private Sub LoadFrm(ByVal pIDD As String, ByVal pMsg As String)
memFrmNum = memFrmNum + 1
FrmObj(memFrmNum) = New Form2
If FrmObj(memFrmNum).InvokeRequired Then
FrmObj(memFrmNum).Invoke(New Action(Of String)(AddressOf LoadFrm), pIDD)
FrmObj(memFrmNum).Invoke(New Action(Of String)(AddressOf LoadFrm), pMsg)
Else
FrmObj(memFrmNum).TextBox1.Text = pIDD
FrmObj(memFrmNum).Label1.Text = pMsg
End If
FrmObj(memFrmNum).Show()
End Sub
In above code I'm trying to load a form multiple times. Getting error on 'AddressOf LoadFrm'.
Please check the attachment.
ErrorOninvoke.zip
Regards,
The problem there is that you're are trying to invoke LoadFrm with Action(Of String) when you should be invoking with Action(Of String, String) because LoadFrm has two string parameters. However, you are targeting .Net 2.0 which doesn't seem to offer Action(Of T1, T2) so here is another way to correct it if you're using VS2010:-
vbnet Code:
' Private Sub LoadFrm(ByVal pIDD As String, ByVal pMsg As String) memFrmNum = memFrmNum + 1 If memFrmNum > 1000 Then memFrmNum = 1 FrmObj(memFrmNum) = New Form2 If FrmObj(memFrmNum).InvokeRequired Then FrmObj(memFrmNum).Invoke(Sub() LoadFrm(pIDD, pMsg)) Else FrmObj(memFrmNum).TextBox1.Text = pIDD FrmObj(memFrmNum).Label1.Text = pMsg End If FrmObj(memFrmNum).Show() End Sub
-
Jul 20th, 2013, 03:49 AM
#80
Lively Member
Re: Understanding Multi-Threading in VB.Net
Oh ok thanks again Niya . I am very new in vb.net. Now the codes are not showing any error, but Form2 is still hanging after loading.. How can I solve this with Multi threading? Please check the attachment file of my last post.
After clicking button on the form1, Open notepad.exe... and you will found Form2 will be hanging up.
How can we do it with Control properties on framework above 2.0?
If you can make any correction on it, please kindly do it.
Thanks again,
regards
Last edited by green.pitch; Jul 20th, 2013 at 04:03 AM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|