473,770 Members | 2,217 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to start a thread with a parameter in framework 2.0?

I have heard theres a new way to start threads with parameters in
framework 2.0, does anyone know how to do that?

this is what i need to do...

Start a thread that executes some stuff, in this case it does gets all
files from a directory. then i need to update the GUI with information
from the thread...

the thread should be started with a parameter, in this case its a string
that contains the path to the files...

Appriciate any code examples.

Thanks in advance.
Nov 23 '05 #1
3 1893
This should help: http://msdn2.microsoft.com/en-us/library/ts553s52.aspx

"JohnnyGr" <jo************ *****@liquidzon e.net> wrote in message
news:yq******** *************** *******@giganew s.com...
I have heard theres a new way to start threads with parameters in
framework 2.0, does anyone know how to do that?

this is what i need to do...

Start a thread that executes some stuff, in this case it does gets all
files from a directory. then i need to update the GUI with information
from the thread...

the thread should be started with a parameter, in this case its a string
that contains the path to the files...

Appriciate any code examples.

Thanks in advance.
Nov 23 '05 #2

JohnnyGr wrote:
I have heard theres a new way to start threads with parameters in
framework 2.0, does anyone know how to do that?

this is what i need to do...

Start a thread that executes some stuff, in this case it does gets all
files from a directory. then i need to update the GUI with information
from the thread...

the thread should be started with a parameter, in this case its a string
that contains the path to the files...

Appriciate any code examples.

Thanks in advance.


AFAIK, the new way for working with threads (and the easiest one, as it
seems) is given by the BackgroundWorke r control. You add one of these
beasts to your Form and call your threaded method from its DoWork
event. When the thread finishes, the BackgroundWorke r raises an event
on the UI thread where you can get any results back from threaded
method:

'--------------------------------------------------------
Function ScanFiles(ByVal Path As String) As String()
'--------------------------------------------------------
Dim Result() As String
'... Scan the file system ...'
Return Result
End Function

'--------------------------------------------------------
Private Sub AsyncScanFiles_ DoWork( _
ByVal Sender As System.Object, _
ByVal e As System.Componen tModel.DoWorkEv entArgs) _
Handles AsyncScanFiles. DoWork
'--------------------------------------------------------
'We're running on a secondary thread
Dim Path As String = CType(e.Argumen t, String)
e.Result = ScanFiles(Path)
End Sub

'--------------------------------------------------------
Private Sub AsyncScanFiles_ RunWorkerComple ted( _
ByVal sender As Object, _
ByVal e As System.Componen tModel.RunWorke rCompletedEvent Args _
) Handles AsyncScanFiles. RunWorkerComple ted
'--------------------------------------------------------
'We're running on the UI thread
If e.Error IsNot Nothing Then
'handle any exception raised in the thread
ElseIf Not e.Cancelled Then
Dim Result() As String = CType(e.Result, String())
'...Use the returned file list...'
End If
End Sub

In the above example, I added a BackgroundWorke r control to the form
and named it AsyncScanFiles. Somewhere in my code I called the
control's RunWorkerAsync method, passing the path as an Object
parameter:

AsyncScanFiles. RunWorkerAsync( Path)

Simple, eh? :-D

Another approach would be to handle it yourself. The Thread class
allows for passing a single parameter of type Object to the target
method. The problem is getting a result back. Besides, you must not
access the UI from your secondary thread. See, the UI should only be
acessed from the main thread (actually, from the thread that created
the UI elements, which is the main thread of the app).

The "protocol" I use is similar to the backgroundworke r control. I use
auxiliary methods to lauch the thread and to get results delivered to
the UI.
Imports SysThread = system.Threadin g

'--------------------------------------------------------
Function ScanFiles(ByVal Path As String) As String()
'--------------------------------------------------------
Dim Result() As String
'... Scan the file system ...'
Return Result
End Function

'--------------------------------------------------------
Private Sub AsyncScanFiles( ByVal PathString As Object)
'--------------------------------------------------------
Dim Path As String = CType(PathStrin g, String)
Dim Result() As String = ScanFiles(Path)
ScanFilesDone(R esult)
End Sub

'... somewhere in my code
Dim T As New SysThread.Threa d(AddressOf AsyncScanFiles)
T.Start(Path)

Notice that the method AsyncScanFiles passes the result to another
auxiliary method, called ScanFilesDone. It's this method that brings
the result back to the UI thread. You can detect if you're outside the
UI thread by checking the Form's InvokeRequired property (this property
is actually inherited from the Control class). If InvokeRequired
returns true, it means that the current thread is other than the main
thread, and so you *must not* touch the UI from there. You need to
transfer control to the main thread using the Form's BeginInvoke method
(which is also inherited from the Control class).

Private Delegate Sub ScanFilesHandle r(ByVal Result() As String)

'...
Sub ScanFilesDone(B yVal Result() As String)
If Me.InvokeRequir ed Then
'We're still out of the UI thread
Dim T As New ScanFilesHandle r(AddressOf ScanFilesDone)
Dim Params() As Object = {Result}
Me.BeginInvoke( T, Params)
Else
'We're in the UI thread.
'By this time, the calling thread is long gone
For Each Item As String In Result
'Show the files in the UI
Next
End If
End Sub

In ScanFilesDone, the Form's InvokeRequired tells me that we're not on
the main thread. ScanFilesDone calls itself again, this time
indirectly, by using the Form's BeginInvoke method. To do this I had to
declare a new delegate type, which I called ScanFilesHandle r. This is
because the Form's BeginInvoke method requires a typed delegate as
parameter.

HTH.

Regards,

Branco.

Nov 23 '05 #3
Thank you for that answer, that answered my question and even more.

Ill think ill go with the backgroundworke r alternative since that is
the closest one to my needs as i see it.

Best regards
//Johnny

Branco Medeiros wrote:
JohnnyGr wrote:
I have heard theres a new way to start threads with parameters in
framework 2.0, does anyone know how to do that?

this is what i need to do...

Start a thread that executes some stuff, in this case it does gets all
files from a directory. then i need to update the GUI with information
from the thread...

the thread should be started with a parameter, in this case its a string
that contains the path to the files...

Appriciate any code examples.

Thanks in advance.

AFAIK, the new way for working with threads (and the easiest one, as it
seems) is given by the BackgroundWorke r control. You add one of these
beasts to your Form and call your threaded method from its DoWork
event. When the thread finishes, the BackgroundWorke r raises an event
on the UI thread where you can get any results back from threaded
method:

'--------------------------------------------------------
Function ScanFiles(ByVal Path As String) As String()
'--------------------------------------------------------
Dim Result() As String
'... Scan the file system ...'
Return Result
End Function

'--------------------------------------------------------
Private Sub AsyncScanFiles_ DoWork( _
ByVal Sender As System.Object, _
ByVal e As System.Componen tModel.DoWorkEv entArgs) _
Handles AsyncScanFiles. DoWork
'--------------------------------------------------------
'We're running on a secondary thread
Dim Path As String = CType(e.Argumen t, String)
e.Result = ScanFiles(Path)
End Sub

'--------------------------------------------------------
Private Sub AsyncScanFiles_ RunWorkerComple ted( _
ByVal sender As Object, _
ByVal e As System.Componen tModel.RunWorke rCompletedEvent Args _
) Handles AsyncScanFiles. RunWorkerComple ted
'--------------------------------------------------------
'We're running on the UI thread
If e.Error IsNot Nothing Then
'handle any exception raised in the thread
ElseIf Not e.Cancelled Then
Dim Result() As String = CType(e.Result, String())
'...Use the returned file list...'
End If
End Sub

In the above example, I added a BackgroundWorke r control to the form
and named it AsyncScanFiles. Somewhere in my code I called the
control's RunWorkerAsync method, passing the path as an Object
parameter:

AsyncScanFiles. RunWorkerAsync( Path)

Simple, eh? :-D

Another approach would be to handle it yourself. The Thread class
allows for passing a single parameter of type Object to the target
method. The problem is getting a result back. Besides, you must not
access the UI from your secondary thread. See, the UI should only be
acessed from the main thread (actually, from the thread that created
the UI elements, which is the main thread of the app).

The "protocol" I use is similar to the backgroundworke r control. I use
auxiliary methods to lauch the thread and to get results delivered to
the UI.
Imports SysThread = system.Threadin g

'--------------------------------------------------------
Function ScanFiles(ByVal Path As String) As String()
'--------------------------------------------------------
Dim Result() As String
'... Scan the file system ...'
Return Result
End Function

'--------------------------------------------------------
Private Sub AsyncScanFiles( ByVal PathString As Object)
'--------------------------------------------------------
Dim Path As String = CType(PathStrin g, String)
Dim Result() As String = ScanFiles(Path)
ScanFilesDone(R esult)
End Sub

'... somewhere in my code
Dim T As New SysThread.Threa d(AddressOf AsyncScanFiles)
T.Start(Path)

Notice that the method AsyncScanFiles passes the result to another
auxiliary method, called ScanFilesDone. It's this method that brings
the result back to the UI thread. You can detect if you're outside the
UI thread by checking the Form's InvokeRequired property (this property
is actually inherited from the Control class). If InvokeRequired
returns true, it means that the current thread is other than the main
thread, and so you *must not* touch the UI from there. You need to
transfer control to the main thread using the Form's BeginInvoke method
(which is also inherited from the Control class).

Private Delegate Sub ScanFilesHandle r(ByVal Result() As String)

'...
Sub ScanFilesDone(B yVal Result() As String)
If Me.InvokeRequir ed Then
'We're still out of the UI thread
Dim T As New ScanFilesHandle r(AddressOf ScanFilesDone)
Dim Params() As Object = {Result}
Me.BeginInvoke( T, Params)
Else
'We're in the UI thread.
'By this time, the calling thread is long gone
For Each Item As String In Result
'Show the files in the UI
Next
End If
End Sub

In ScanFilesDone, the Form's InvokeRequired tells me that we're not on
the main thread. ScanFilesDone calls itself again, this time
indirectly, by using the Form's BeginInvoke method. To do this I had to
declare a new delegate type, which I called ScanFilesHandle r. This is
because the Form's BeginInvoke method requires a typed delegate as
parameter.

HTH.

Regards,

Branco.

Nov 23 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
8865
by: vee_kay | last post by:
Ihave a written aprogram in C which implements _beginthread(to create a thread) and _endthread(to end a thread).The program need to write a string of date n time to a file for each succesful thread created. I had put a delay of a second so that the thread and io operation will occur after a second. Now i need to implement another thing which i need to make sure the run was actually a second. This is because if i add another delay of...
5
1738
by: Kenneth | last post by:
Hi, I've upgraded to .NET 2003 and I opened an .NET 2002 app and let the new IDE convert it to .NET 2003 project. Then I tried to start the application but it keeps on saying "Error while trying to run project. Unable to start debugging on the web server. The project is not configured to be debugged. Click Help for more information".
16
4223
by: Serdar Kalaycý | last post by:
Hi everybody, My problem seems a bit clichè but I could not work around. Well I read lots of MSDN papers and discussions, but my problem is a bit different from them. When I tried to run the project in debug mode (by hitting F5) it gives an error message "Error while trying to run project: Unable to start debugging on the web server.
1
1195
by: homer | last post by:
Hello, everybody, When I try to create an ASP.NET 1.1 Application, I got: VS.Net has detected that the Specified Web Server Is Not Running ASP.NET Version 1.1" Error Message. I am running VS.net 2003 Pro on w2k. My web server is the local IIS5. I have my windows and IIS running for a while and VS.Net is a new install. I have run aspnet_regiis –I, and regsvr32 aspnet_isapi.dll under commend
9
3215
by: Tim D | last post by:
Hi, I originally posted this as a reply to a rather old thread in dotnet.framework.general and didn't get any response. I thought it might be more relevant here; anyone got any ideas? My questions are below... "David Good" wrote: > We have a network running both Win2k and Win2k3 webservers and our web sites > reside on a UNC network share that happens to be a Network Appliance NAS.
11
1694
by: parsifal | last post by:
In Java I can start a thread and write the function in-place. So, you could do, in pseudocode: def someFunc: thread.new( def summit: doSomeStuff() ) How can I do that in C#?
8
1699
by: Carl Heller | last post by:
If I'm creating a class to do some work that I want threaded out, where's the best location to call ThreadStart? Or does it depend on the nature of the work? a. Call it outside the class, giving it the starting method of the class? b. Have the class create the thread itself? ie: x = new WorkerClass(); ioThread = new Thread(new ThreadStart(x.StartWork));
0
2948
by: HeroOfSpielburg | last post by:
Hello, I'm new to the realm of .NET application creation, so please forgive my ignorance. I have been tasked with debugging a problem that arises with using a DLL that contains managed and unmanaged code in concert with a managed application that makes calls to the DLL. This problem has been cropping up for a while, but the debugger provides very little information (from what I can tell) as to what exactly is the problem.
5
3644
by: Benjamin The Donkey | last post by:
Is there something in C# that is similar to Java's Thread.yield? Currently I am using the 1.1 framework.
0
9619
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9454
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10260
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10102
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9910
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8933
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5354
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3609
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.