The first issue is that IP
is scoped to the method Main
. You'll need to declare IP
somewhere th1T
can get to if you truly want to share it.
static string IP = "127.0.0.1"
static void Main(string[] args)
{
// do some work and start th1T()
}
static void th1T()
{
while (true)
{
var ping = new Ping();
ping.Send(IP);
}
}
Here you'll be able to reach IP
even if th1T
is running on a different thread. There are some other options as well though, like injecting the IP into th1T
when the thread is started. To do that you'd have to change the signature of th1T
to this:
static void th1T(object data)
and you'd have to change the code a little:
static void th1T(object data)
{
while (true)
{
var ping = new Ping();
ping.Send(data as string);
}
}
You could then start that on another thread like this:
Thread newThread = new Thread(th1T);
newThread.Start(IP);
Threading is very much a subjective subject. If the value you're referencing from another thread is being read only, like in your example, and it's only set once by the controller (the class starting the work), then it's absolutely valid to share the variable between threads. Many however will argue to their death on this.
We can only speak in generalities in respect to this issue. For example, in general it's more appropriate to inject the value to avoid race conditions and dead locks. But again, that would really depend on what you're doing with the value. You can't inject the value if you're reading a flag from one thread that's set by another. In that case you have to safely synchronize the value.
There's no need to continue because as you see the rabbit hole only gets deeper.