How to create thread according to integer value? [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I'm trying to create thread according to integer value. For example if the variable is '5', program should create 5 threads or variable is '2', program should create 2 threads, etc. But I can't understand which path I must follow.

It's just a matter of creating the Thread and start it. But I wouldn't suggest you to handle the thread explicitly, but to use Tasks or ThreadPool in order to execute multithreading work.
using System;
using System.Threading;
public class Program
{
public static void Main()
{
int numberOfRequestedThreads = 3;
for (int i = 0; i < numberOfRequestedThreads; i++)
{
var tempThread = new Thread(new ThreadStart(DoWork));
tempThread.Name = i.ToString();
tempThread.Start();
}
}
public static void DoWork()
{
Console.WriteLine("Thread#{0} is now working!", Thread.CurrentThread.Name);
}
}

Related

For cycle always give same output [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 months ago.
Improve this question
1. Summarize the problem
The following for cycle keeps on running as i want, but always give me the same clicked button that is "0".
It does not give me an error. But by playing the game i can see that it's always the same number.
2. Describe what you've tried
I've tried searching around the internet for people like me. but sadly i couldn't find anything.
3. Show some code
Code that i'm talking about.
int ButtonNum;
public void Start()
{
for (int i = 0; i < ButtonsPage.Length; i++)
{
ButtonsPage[i].GetComponent<Button>().onClick.AddListener(delegate { ButtonClicked(ButtonNum); });
}
}
public void ButtonClicked(int i)
{
Debug.Log("Clicked" + i);
if (WhichType == "Nose")
{
NoseColor.sprite = NosesColor[i];
NoseOutline.sprite = NosesOutline[i];
}
//ButtonNum will be used to say which one is clicked. Still haven't add it though cause i wanted to fix this problem before
}
You are not modifying ButtonNum in any way, I assume the goal is to use i as button number, try changing your code to:
public void Start()
{
for (int i = 0; i < ButtonsPage.Length; i++)
{
var temp = i;
ButtonsPage[i].GetComponent<Button>().onClick.AddListener(delegate { ButtonClicked(temp); });
}
}
Temporary variable is required due to how closures work in C#.

How to access my running code Thread from a GUI Textbox. C# Forms [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I am trying to access a method, and a variable in that method, that is also in a separate thread from a GUI Textbox in Windows Forms.
Every other question people have is how to go the other way by accessing the GUI from a separate thread that's the opposite of what I'm trying to do.
public ClientWindow()
{
InitializeComponent();
var ItemThread = new Thread(new ThreadStart(ItemRun));
ItemThread.Start();
}
public void ItemRun()
{ //..
}
public void Return(object sender, KeyEventArgs e)
{ //need to access a variable in ItemRun() from here
}
Thanks for any answers.
You just need to make your Variable/s Global, also if you need thread safety you need use some sort of locking mechanism
// create global variable
private volatile int somevar;
// create a sync object to lock
private int _sync = new object();
...
public void ItemRun()
{
// make sure you lock it
// if there might be race conditions or you need thread safety
lock(_sync)
{
// update your global variable
somevar = 3;
}
}
public void Return(object sender, KeyEventArgs e)
{
// lock it again if you need to deal with race conditions
// or thread safty
lock(_sync)
{
Debug.WriteLine(somevar);
}
}
Update
volatile (C# Reference)
The volatile keyword indicates that a field might be modified by
multiple threads that are executing at the same time. Fields that are
declared volatile are not subject to compiler optimizations that
assume access by a single thread. This ensures that the most
up-to-date value is present in the field at all times.

Total execute time in thread [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Here's my code:
foreach (var obj in listObj)
{
Thread t = new Thread(()=> dosomething(obj))
t.IsBackground = true;
t.Start();
Thread.Sleep(5);
}
The listObj has 500 obj, the dosomething function may take 100 milliseconds and the total time for ending the loop is 9 seconds. I don't know why it take 9s. Please help.
Inside the dosomething a url is called using httprequest.
You can create a simple test program for that:
void DoSomething()
{
Thread.Sleep(100);
}
void Test()
{
DateTime dt = DateTime.Now;
for (int i=0; i<500; i++)
{
Thread t = new Thread(() => DoSomething());
t.IsBackground = true;
t.Start();
Thread.Sleep(5);
}
MessageBox.Show(DateTime.Now.Subtract(dt).TotalSeconds.ToString() );
}
This takes on my slow old PC about 2.8 sec.
When I comment all Thread.Sleep calls I get cca 2 seconds.
The limits of maximum numer of threads for 1 process are relatively high, so this is not a problem.
When you want to have detailed info about what is going on, you can use Sysinternals Process monitor. There you will see what is going on. Maybe some libraries are loading or something like that.
It should roughly be 500*5/1000 = 2.5 secs + overhead(for other statements in for loop)
There's no way it'll be taking 9s. Recheck your debug statements used to calculate time duration

How to use the thread to show something on the label on the form? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
i have a method
public static string MyWrite2()
{
string p = "hi";
for (int i = 0; i < 20; i++)
{
p += "kk";
}
return p;
}
and i want to write a thread which when i click on btn1 it call MyWrite2 and put the result on label1, how can i do it?
You can use Invoke() method on a label1 and pass a method which does the writing as an argument to the Invoke() method.
Using anonymous method it would be sth like:
label1.Invoke(new MethodInvoker(delegate
{
label1.Text = MyWrite2();
}
));
In the other thread.

Using lock( ) C# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Why is this lock not working?
CheckActivity is generated from Mouse/Keyboard Windows hook. Any hint how to make this lock to work?
private void CheckActivity(KeyboardMouseKey k)
{
lock(this)
{
if (_map)
{
_map = false;
if (openFileDialogSelectAudio.ShowDialog() == DialogResult.OK)
MapSound(k, openFileDialogSelectAudio.FileName);
}
else
{
///play
foreach (var m in _mappings.Where(m => m.Key.Equals(k)))
m.Value.Play();
}
UpdateGui();
}
}
You are using lock(this).
If Check Activity is called on different objects, lock(this) will not prevent for making sure that only one thread is executing CheckActivity (which appears to be the purpose of the lock)
Use lock on static object to make it work.
Example:
private static readonly object lockObj = new object();
...
lock(lockObj)
{
....
}

Categories