OK, so first of all- creating a new thread does have some minimal overhead, but you're only creating the thread once (or a few times)... so unless you're creating hundreds of threads (which you shouldn't be), then you will not need to worry about the overhead.
Let's look at your first example:
Thread thread;
thread = new Thread(new ThreadStart(DoNetworkThing));
// you should set the thread to background, unless you
// want it to live on even after your application closes
thread.IsBackground = true;
thread.Start();
If you were sticking with that model, the DoNetworkThing
function would look like this:
void DoNetworkThing()
{
while(someConditionIsTrue)
{
// do the networking stuff here
}
}
I presume that in your next attempt you did something like this:
Thread thread = new Thread(()=>
{
while(true)
{
DoNetworkThing();
}
});
thread.IsBackground = true;
thread.Start();
Both approaches are fine, but the only difference is the content of DoNetworkingThing
. In the second approach it will look like this:
void DoNetworkThing()
{
// do the networking thing, but note
// that this time your infinite while
// loop is outside the function
}
Now you said that both of these attempts are really slow, but nothing given in your examples would indicate that there should be any noticeable performance impact. It would be great if you can:
- Give us an example that would demonstrate the slow down.
- Tell us how many cores you have on the machine that the game is running on.
Finally, if you're mingling with threads then I would STRONGLY suggest that you pickup a good book on multithreading and really familiarize yourself with the concepts behind it, go through the exercises and write a couple of simple programs. It will take you a couple of months, but if you're not familiar with threading then it will help you learn how to avoid a lot of ugly mistakes.
A lot of people recommend Joe Duffy's Concurrent Programming on Windows, but feel free to check some other C# multithreading books too.