Click here to Skip to main content
15,890,506 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
Is there a way to make this code shorter? Whenever I call function in thread I have to do this, making two function for one, maybe you think I'm dumb, but I really need a shortcut to this, I make my code looks stupid using this method. It looks like this:

C#
public void StartServer(bool InThread = false)
        {
            if (InThread)
            {
                Thread t = new Thread(CallStartServer);
                t.Start();
            }
            else CallStartServer();
        }

        private void CallStartServer()
        {
            TcpListener listener = new TcpListener(IPAddress.Any, Port);
            while (true)
            {
                if (listener.Pending())
                {
                    TcpClient client = listener.AcceptTcpClient();
                    if (OnClientConnected != null) OnClientConnected(client);
                }
            }
        }


it will really be appreciated if you share a shorter version.
Posted
Updated 24-Sep-15 12:35pm
v2
Comments
PIEBALDconsult 24-Sep-15 15:19pm    
Use an anonymous method?
Have StartServer pass itself to the thread with a parameter of false?
SrgjanX 24-Sep-15 15:19pm    
how? :/
PIEBALDconsult 24-Sep-15 15:25pm    
See https://msdn.microsoft.com/en-us/library/vstudio/system.threading.parameterizedthreadstart(v=vs.110).aspx
Matt T Heffron 24-Sep-15 17:29pm    
Are you sure about that link?
The example I see there has nothing to do with threading.
(I think MSDN is broken there.)
The .NET Framework 4 version is correct:
https://msdn.microsoft.com/en-us/library/vstudio/system.threading.parameterizedthreadstart(v=vs.100).aspx
PIEBALDconsult 24-Sep-15 19:50pm    
Really? I get ParameterizedThreadStart Delegate as expected.

I think this is what PIEBALDconsult was referring to:
C#
public void StartServer(bool InThread = false)
{
  if (InThread)
  {
    Thread t = new Thread(it => StartServer((bool)it));
    t.Start(false);
  }
  else
  {
    TcpListener listener = new TcpListener(IPAddress.Any, Port);
    while (true)
    {
      if (listener.Pending())
      {
        TcpClient client = listener.AcceptTcpClient();
        if (OnClientConnected != null)
          OnClientConnected(client);
      }
    }
  }
}

The lambda in the Thread constructor is required because the ParameterizedThreadStart delegate to that constructor needs the argument to be type object.

Edit: MTH
As PIEBALDconsult noted in the comments below. The thread creation can be simplified a bit:
C#
if (InThread)
{
  Thread t = new Thread(() => StartServer(false));
  t.Start();
}
else

Or, if you just want to start the thread and then forget about it:
C#
if (InThread)
{
  new Thread(() => StartServer(false)).Start();
}
else

but you won't be able to do anything to the thread after that.
(That's pretty much like having the local variable t go out of scope right after starting the thread!)
 
Share this answer
 
v2
Comments
PIEBALDconsult 24-Sep-15 19:51pm    
Yep, except I avoid Lambdas and would have used an Anonymous Method.
And I probably wouldn't have a local variable to hold the Thread for no reason, maybe use Join to wait for the thread to exit.
Matt T Heffron 24-Sep-15 20:05pm    
Isn't a lambda pretty much a different syntax for an anonymous method? Here I just use it for the wrapper, but, yes it could be the "body" of the method, invoked either directly or by the new thread.

I also agree about the local variable for the Thread. I was trying to keep it as close to the original and still demonstrate the concept.
PIEBALDconsult 24-Sep-15 20:09pm    
I can't read Lambdas so I don't write them. :D

I guess a thread pool references the thread.

And in the Lambda you should just send false to the method or you have an infinite loop, yes?
Matt T Heffron 24-Sep-15 20:13pm    
Reading lambdas is not a problem for me...I used to do lots of work in Lisp! Just a different syntax for the same semantics.
Yes, the lambda could be parameterless and just pass the false directly which would have removed the parameter from the .Start(). Just general case vs. specific case.
Matt T Heffron 24-Sep-15 20:14pm    
Also, there's a note in the Thread class description: It is not necessary to retain a reference to a Thread object once you have started the thread. The thread continues to execute until the thread procedure is complete. I learned something new...
Why making shorter something which is already based on wrong idea? The whole idea to create a new thread in a call is quite bad. There are different, much better variants, such as having a permanently working thread you feed with tasks (delegate instances); the tasks go in a blocking queue, so when there is no another task, a thread goes in a wait state, which does not waste any CPU time.

See, for example, my article Simple Blocking Queue for Thread Communication and Inter-thread Invocation[^] (and pay attention for the alternative, http://www.codeproject.com/script/Articles/ListAlternatives.aspx?aid=149540[^]).

And so on…

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900