I'm wondering how I can send a variable from one thread to another in a c# console application. For example,
using System;
using System.Threading;
namespace example
{
class Program
{
static void Main(string[] args)
{
int examplevariable = Convert.ToInt32(Console.ReadLine ());
Thread t = new Thread(secondthread);
t.Start();
}
static void secondthread()
{
Console.WriteLine(+examplevariable);
}
}
}
I want to make "secondthread" recognize "examplevariable".
There is an overload to Thread.Start() that takes a parameter as object. You can pass your main thread variable to that and cast it as your variable type
using System;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int examplevariable = Convert.ToInt32(Console.ReadLine());
Thread t = new Thread(secondthread);
t.Start(examplevariable);
}
static void secondthread(object obj)
{
int examplevariable = (int) obj;
Console.WriteLine(examplevariable);
Console.Read();
}
}
}
if you want to pass multiple variable then use a model class and use property binding like below
using System;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
TestModel tm = new TestModel();
tm.examplevariable1 = Convert.ToInt32(Console.ReadLine());
tm.examplevariable2 = Console.ReadLine();
Thread t = new Thread(secondthread);
t.Start(tm);
}
static void secondthread(object obj)
{
TestModel newTm = (TestModel) obj;
Console.WriteLine(newTm.examplevariable1);
Console.WriteLine(newTm.examplevariable2);
Console.Read();
}
}
class TestModel
{
public int examplevariable1 { get; set; }
public string examplevariable2 { get; set; }
}
}
Hope this will help
An easy way to do this, but might not work in all scenarios, would be to define a static variable on the class and assign the value read in from the console to the static variable. Like so:
class Program
{
static int examplevariable;
static void Main(string[] args)
{
examplevariable = Convert.ToInt32(Console.ReadLine ());
Thread t = new Thread(secondthread);
t.Start();
}
static void secondthread()
{
Console.WriteLine(+examplevariable);
}
Also, see this question on how to pass parameters to a Thread:
ThreadStart with parameters
Related
I am trying to assign value to my variable in default constructor and Thread Construction. However, I am unable to identify how to solve this issue.
I have created a for loop through which I am assigning my value as well as to Start the Thread.
How can I solve ThreadStart(InitializeServer(I))?
-> Error: Method name expected
What is the other way around for this. ServerInitialization.Start();
-> If I use workerThread.Start() will all individual thread would start? Example Such as Server 1, Server 2?
ServerInitialization.cs
using System;
using System.Threading;
namespace MyApplication
{
public class ServerInitialization
{
public int serverID;
static private int ServersInStore = MainApplication.numofServers;
public ServerInitialization(int serverNum)
{
this.serverID = serverNum;
}
public static void InitializeServer(int sId)
{
ServerInitialization _id = new ServerInitialization(sId);
_id.serverID = sId;
}
public static void AssignServer(int totalServers)
{
for (int i = 0; i<totalServers; ++i)
{
Thread workerThread = new Thread(new ThreadStart(InitializeServer(i)));
ServerInitialization.Start();
}
}
}
MainApplication.cs
using System;
using System.Threading;
namespace MyApplication
{
public class MainApplication
{
public static int numofServers = 0;
static void Main(string[] args)
{
Console.WriteLine("How servers required?");
numofServers = int.Parse(Console.ReadLine());
ServerInitialization.AssignServer(numofServers);
}
}
}
Recreating my C# issue in Java project.
GenerateServer.java
import java.util.Scanner;
public class GenerateServer {
protected static int NumOfServers=4;
public static void main(String[] args) {
// TODO Auto-generated method stub
Server.InitializeServer();
}
}
Server.java
public class Server implements Runnable{
private int serverID;
//private Customer atCounter;
static private int ServersInStor=GenerateServer.NumOfServers;
public Server(int serverID)
{
this.serverID=serverID;
}
public static void InitializeServer()
{
for (int i=0; i<GenerateServer.NumOfServers; ++i)
{
Thread Server = new Thread(new Server(i));
Server.start();
}
}
#Override
public void run() {
// TODO Auto-generated method stub
}
}
Looks like you can just use an anonymous lambda function
Thread workerThread = new Thread(new ThreadStart(() => InitializeServer(i)));
Or in short:
Thread workerThread = new Thread(() => InitializeServer(i));
For example we have such a class:
namespace ConsoleApp1
{
public class Program
{
public int x = 0;
public int y = 1;
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Program program = new Program();
program.RunScript(Console.ReadLine());
}
public void RunScript(string script)
{
//....
}
public void CallMethod1()
{
}
public void CallMethod2()
{
}
}
}
And in the console I want to enter an expression for execution, in the language C#:
"if(x > y){CallMethod1();}else{CallMethod2();}"
how can this expression be executed? I've seen examples with Roslyn https://learn.microsoft.com/en-us/archive/msdn-magazine/2017/may/net-core-cross-platform-code-generation-with-roslyn-and-net-core
but they call static functions or functions from the new namespace, but I need to call a function that is already in the current namespace
This question already has answers here:
When to use static methods
(24 answers)
Closed 2 years ago.
I always knew that I have to use static methods but I wonder why?
As you can see below I have to make "MigrateDatabase" Static
using System;
namespace OdeToFood
{
public class Program
{
public static void Main(string[] args)
{
MigrateDatabase();
}
private static void MigrateDatabase()
{
//.....
}
}
}
Let's just be clear, the only reason MigrateDatabase has to be static in this case is because you're calling it from a static method (Main). If instead MigrateDatabase was an instance method on a class, you could instantiate that class and call it
using System;
namespace OdeToFood
{
public class Program
{
public static void Main(string[] args)
{
var migration = new Migration();
migration.MigrateDatabase();
}
}
public class Migration
{
private void MigrateDatabase()
{
//.....
}
}
}
You could also put it as a instance method on Program if you're instantiating an instance of that class
using System;
namespace OdeToFood
{
public class Program
{
public static void Main(string[] args)
{
var program = new Program();
program.MigrateDatabase();
}
private void MigrateDatabase()
{
//.....
}
}
}
I have a static member:
namespace MyLibrary
{
public static class MyClass
{
public static string MyMember;
}
}
which I want to access like this:
using MyLibrary;
namespace MyApp
{
class Program
{
static void Main(string[] args)
{
MyMember = "Some value.";
}
}
}
How do make MyMember accessible (without MyClass.) to MyApp just by adding using MyLibrary?
C# doesn't allow you to create aliases of members, only of types. So the only way to do something like that in C# would be to create a new property which is accessible from that scope:
class Program
{
static string MyMember
{
get { return MyClass.MyMember; }
set { MyClass.MyMember = value; }
}
static void Main(string[] args)
{
MyMember = "Some value.";
}
}
It's not really an alias, but it accomplishes the syntax you're looking for.
Of course, if you're only accessing / modifying a member on MyClass, and not assigning to it, this can be simplified a bit:
class Program
{
static List<string> MyList = MyClass.MyList;
static void Main(string[] args)
{
MyList.Add("Some value.");
}
}
I have a host class which launches an instance of another class on a new thread like so:
I am referencing this MSDN article according to which, Class2.P1 should NOT be null.
LINK: http://msdn.microsoft.com/en-us/library/system.threading.threadstart.aspx
Am I missing anything obvious?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
new Host().DoWork();
}
}
public class Host {
Class2Parent c = new Class2();
Thread t;
public void DoWork() {
c.P1 = new Class3();
t = new Thread(c.Start);
t.Start();
}
}
public class Class2Parent {
public Class3 P1 = null;
public virtual void Start() {}
}
public class Class2 : Class2Parent {
public Class3 P1 = null;
public override void Start() {
Console.WriteLine(P1 == null); // this is always true
}
}
public class Class3
{}
}
You can try to create a new thread using a timer variable just like that :
private Timer m_RequestTimer;
public void Begin()
{
// Timer check
if (m_RequestTimer != null)
{
m_RequestTimer.Change(Timeout.Infinite, Timeout.Infinite);
m_RequestTimer.Dispose();
m_RequestTimer = null;
}
m_RequestTimer = new System.Threading.Timer(obj => { c.Start(); }, null, 250, System.Threading.Timeout.Infinite);
}
}
where m_RequestTimer is an attribute of your class host and Begin a method of Host.
I hope it will help you =)