Link to home
Start Free TrialLog in
Avatar of asmyatt
asmyatt

asked on

looping a BackgroundWorker

I have a background worker that recieves data from a server and writes it to a text box. How can I loop this so that after it recieves one set of data and writes it to the text box it will continue to listed for more data.

What I current;y do is call this:

backgroundWorker2.RunWorkerAsync();

when the form loads. It will work fine but of course doesn't continue to listen for more data.

Thanks
Avatar of vo1d
vo1d
Flag of Germany image

do you get the data with the same worker?
normally, the backgroundworker class is only used do run a single asny operation, not for using network listening.
what you could do is run the worker again after RunWorkerCompleted event is fired.
how does the data comes from the server?
do you read some date from a database with your backgroudnworker or do you read some network data?
Avatar of asmyatt
asmyatt

ASKER

I read network data, no data from a database. The data comes across a socket as string, and I do some processing with received string. You can think of it like a chat program. A client sends data to the server and the server sends the message to all of the clients connected to it.

I did manage to get it to work. At the end of RunWorkerCompleted I just called backgroundWorker2.RunWorkerAsync(); again and it starts the background worker like I wanted it too.  

 I'm new to C# so I would like to hear ideas of how this should be done if this way is not recommended.

Thanks
Generally, for network operations, BackgroundWorker DoWork function must look like this (pseudo-code):

while ( true )
{
    Wait for data
    Handle data
}

DoWork function executes endless loop handling all incoming data from network connection.
ASKER CERTIFIED SOLUTION
Avatar of vo1d
vo1d
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
it is an example which connects to host.contoso.com on client site.
so you will have to change the IPHostEntry to the machine, were you run the server.