If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

multiple backgroundworkers

Hi,

I am new here.

I am not a professional programmer so please forgive me if I ask something obvious.

I am trying to create a program to log data from several devices connected via tcp/ip.

I want to start each connection in its own thread but I don't know at design time how many devices will be connected.
I decided to use a list of "backgroundworkers" objects. The problem I have now is how to pass the ipaddress and port to open to each thread and the name of the file to store the data.

I have searched the internet looking for a similar problem with several backgroundworkers but all examples use only one backgroundworker.

Re: multiple backgroundworkers

If you need to use multiple threads, then you're just going to need to do it the old-fashioned way and make multiple Threading.Thread objects and point them to the subroutines they're supposed to run (it's actually not hard at all to do).

BackgroundWorker is pretty much "Threading for Dummies" in that it's an excellent tool to teach a new programmer how to run work on a second thread and is great for simple tasks; but with it's simplicity comes the price of flexibility.

Re: multiple backgroundworkers

I would suggest using the ThreadPool. You just call QueueUserWorkItem as many times as you need. The first argument is a delegate for the method you want to execute and the second argument is the data you want to pass to that method. I'm not going to provide a complete solution but in your case you'd start out by defining a type that could contain the data required, i.e. the IP address and the port number:

vb.net Code:

FriendStructure Address

Public IPAddress AsString

Public PortNumber AsInteger

EndStructure

You'd then write a method that accepted an object of that type and used it. Note that this method must match the signature of the WaitCallback delegate, so it must have one parameter of type object:

The ThreadPool will queue your work items until a thread pool thread becomes available. That will likely be immediately for each item if the number is low, but if you have a large number of work items then some will wait until others have finished, ensuring you don't grind the system to a halt by trying to run too many tasks at the same time.

Advertiser Disclosure:
Some of the products that appear on this site are from companies from which QuinStreet receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. QuinStreet does not include all companies or all types of products available in the marketplace.