![]() |
![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]()
![]() |

|
| Programming tutorials All Knowledge Info and links to posted here |
![]() |
|
Pass Variables to a New Thread in C#
|
LinkBack | Thread Tools | Display Modes |
|
|
#1 (permalink) |
|
Administrator
Posts: 18,715
Join Date: Jan 2006
Rep Power: 10
IM:
|
Since the ThreadStart delegate doesn't accept parameters, you need to set the parameters somewhere before you create the new thread. What we'll do is create a small class to store the variables, and then create a function in the class to pass into ThreadStart. class myObject { public string myvariable; public void RunThread() { // use myvariable here } } You should really use properties instead of a public variable, but this makes the code sample simpler. The method that you pass into ThreadStart must be void, and accept no parameters. Here's the sample code for creating the object, passing in a variable, and then using the object to create the new thread: myObject m = new myObject(); m.myvariable = "test data that the thread will need"; // Create the new thread, using the function // from the object we created Thread t = new Thread(new ThreadStart(m.RunThread)); t.IsBackground = true; t.Name = "UpdateBookmarkThread"; t.Start(); Now when the thread is started, it will have access to the variables stored in it's own object instance. This technique is very useful if you need to open multiple threads, passing in different information to each. |
|
|
|
|
|
|
![]() |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Wii looks to pass Xbox 360 sales soon | Anilrgowda | wii news | 0 | 14-Aug-2007 12:21 AM |
| EE thread opens at start, not at actual post | Anilrgowda | Microsoft windows vista error | 1 | 10-Jul-2007 12:45 AM |
| PHOTOSHOP TUTORILAS FOR BEGINERS MEGA Thread | AQUARIAN | Graphic tutorials | 51 | 03-Mar-2007 02:24 AM |
| How to set environment variables | Anilrgowda | Linux and Unix Error ! | 0 | 24-Jan-2007 03:18 AM |
| C++: Pointers, Pass by Value, Pass by Reference | Admin | Programming tutorials | 0 | 03-Dec-2006 11:26 PM |