Click here to Skip to main content
15,891,938 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm new to building console applications that will continue to run in the background (in C#). I used Visual Studio 2010 to produce the template, so it produced:

namespace MyNameSpace 
{ 
   class Program 
   { 
      static int Main(string[] args) 
      { 
      }
   } 
}


The program is a TCP listener, so I have a continual loop that listens for TCP messeges. Without getting to far off track, in Class Program I have other routines beside the Main routine, an AcceptCallBack, ReadCallback and others that are defined as public static. I'm trying to instantiate some helper classes that I need to help with the communication, that need to be available in those other routines (ReadCallback and others). Because we don't instatiate the Program class, anything I define at the Program level (so all the other routines can see it) has to be defined as static. So my question is, is there a way (short of passing those instantiated helper objects into all those routines) to make those instantiated helper objects available to the other routines (like a global variable, but one that isn't static). Thanks for any and all help.
Posted

Trying to make anything global is really a bad habit. Why?

Static methods, though, are very useful, but only use them if they work only with the object passed as parameters, plus (optional) return object, nothing else; it will help you to avoid static variables, which are potentially dangerous, especially for multithreading.

Please see my past answer for some explanation of static and instance members:
Type casting in c#[^],
C# windows base this key word related and its uses in the application[^],
What makes static methods accessible?[^].

If you really need a "global" (unique per application domain) object, consider using the singleton pattern:
http://en.wikipedia.org/wiki/Singleton_pattern[^],
http://csharpindepth.com/Articles/General/Singleton.aspx[^].

See also: http://code.google.com/p/google-singleton-detector/wiki/WhySingletonsAreControversial[^].

—SA
 
Share this answer
 
Comments
Afzaal Ahmad Zeeshan 12-Dec-14 9:32am    
+5 :)

Anyways, instead of making anything global just so that other programs and applications can consume it, would be a really bad idea. He can also try to create an API for the application which would act as a gateway to the application resources.

Static variables in real should be used, where there is a property about the class itself, like the MaxValue field in integers in .NET. It would make sense to call the property of the class, rather than calling a new constructor to create the Int16 instance, and then check for the value and so on.

Good answer and solution of the Singletons, I have heard a lot of about them but never tried them, maybe tonight I will try them out...
Sergey Alexandrovich Kryukov 12-Dec-14 12:17pm    
Thank you, Afzaal.
—SA
In your code, you can easily instantiate the Progam class and create an object. Did you even give it a try?

var program = new Program();


Second while working with TCP you might consider looking into the System.Net namespace which would provide the basic but good documents about procedures for working with Networks. You can use classes given there to communicate.

http://msdn.microsoft.com/en-us/library/System.Net(v=vs.110).aspx

To run the app in background you can consider using the BackgroundWorkers etc to run the tasks in the background and capture events.

http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker(v=vs.110).aspx
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 12-Dec-14 1:05am    
It's a very good idea to instantiate not some other class, but the Program class. It looks a bit unusual, and maybe that's why your anonymous down-voter voted 1, but most likely, but probably that person is yet another idiot. I voted 5.

I also would note that background operation is pretty much unrelated to access of static or instance members, but static fields/properties presents the problem for multithreading and performance, and also that other two ways of using threads could be considered. Please see also my answer of explanations on static vs instance.

—SA
Afzaal Ahmad Zeeshan 12-Dec-14 9:28am    
Yes, it really is unusual and sometimes I get into the trouble where I have to use my functions of Program class, and I forget to instantiate the Program class to call those methods. I won't say he was idiot maybe he was someone who didn't get the perfect answer from my side. And yes, Thanks for your vote of 5 Sergey.

I do agree to your claim, these methods are not suited for the multithreading applications. I didn't know of any troubles with the performance (if you're talking about anything apart from memory consumption by these static variables because they remain in the memory for entire life time of program) so I would like to Google for it. :-)
Matthew Menard 12-Dec-14 10:09am    
Pardon my ingorance, but if I have the Project.Main as the entry point, where would I instantiate Program, and where would would I run it's Main routine.
Afzaal Ahmad Zeeshan 12-Dec-14 10:21am    
Since you're going to have just one instance, it doesn't matter where to instantiate it. Program would be instantiated before any procedure can be executed on it, definitely the Main block.
Sergey Alexandrovich Kryukov 12-Dec-14 12:19pm    
Of course it doesn't matter. This is the whole point. Matthew has some misconception here. And one good benefit here: all members of such class can be private.
—SA
No.
If you are in a static method, you can only access static variables and methods, unless you create an instance of a non-static class - in which case you can access it's non-static methods and variables via the instance.

You can fake it - by creating a static variable which contains an instance of a class holding your "global" variables, but frankly that's a mess as well.

Why not do what the WinForms Main method does: creates an instance on the main form and lets it do the work?

C#
static int Main(string[] args)
    {
    MyListener listen = new MyListener();
    while (listen.Run())
         {}
    }
 
Share this answer
 
Comments
Matthew Menard 11-Dec-14 12:34pm    
Right now, my while loop (among other things) make a call to BeginAccept (which runs a BeginAccept Callback) which is a seperate routine inside of the Program class, and that calls BeginRecieve, which runs a BeginRecieve callback, another seperate routine inside the program class. I want to access some communication objects inside these routines that are instantiated inside of Main (the program entry point). Is there a way to make those objects global, or do I need to simply pass them in to the callbacks so those objects can be utilized inside the callbacks. I didn't want to make them static, as they may change in the running of the main routine (and accepting data from TCP clients, etc.)
OriginalGriff 11-Dec-14 14:08pm    
So don't make them static. Make them class level members of a "MyListener" class and create them when you do the MyListener constructor. Then each time you want a Listener, you create new instances and they don't mess about with each other. That way, the data for one client remains with the client - and if you want to share data between clients, then you pass a request back to whatever created the clients in the first place, and it handles the transfer. Clients shouldn't know about other clients unless they explicitly create them.
Matthew Menard 11-Dec-14 16:24pm    
Thanks for the response. I'll give that a go.

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