Total execute time in thread [closed] - c#

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

Related

How do I run a bunch of threads in x amount of time when they all have a thread.sleep? [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 2 years ago.
Improve this question
Full instructions: https://pasteboard.co/J2OX03H.png
Running Thread.Sleep on each thread seems to be preventing the Timer's ElapsedEventHandler from recalling Timer_Elapsed (FixedThreads) every x time causing it to print the threads way too fast. My goal is to have ScheduleThreads launch FixedThreads (prints threads info) every 15 seconds even if some of the threads don't finish executing/sleeping on time.
using FT = FixedThreads.FixedThreads;
using Timer = System.Timers.Timer;
namespace ScheduledThreads
{
class ScheduledThreads
{
static void Main(string[] args)
{
var timer = new Timer(15000);
timer.Elapsed += new ElapsedEventHandler(Timer_Elapsed);
timer.Enabled = true;
while (timer.Enabled)
{
var info = Console.ReadKey(true);
if (info.KeyChar == 'e')
{
timer.Enabled = false;
}
}
}
static void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
FT.Main(null);
}
}
}
I call FixedThreads in ScheduledThreads
public class FixedThreads
{
public static void Main(string[] args)
{
Random random = new Random();
ThreadPool.SetMinThreads(100, 100);
for (int task = 0; task < 1000; task++)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(Execute), task);
Thread.Sleep(random.Next(5, 801)); //this prevents schedule to work if there's more than 10-15 threads/tasks
}
}
static void Execute(object callback)
{
Console.WriteLine($"Thread Id: {Thread.CurrentThread.ManagedThreadId}");
Thread.CurrentThread.Name = callback.ToString();
Console.WriteLine($"Thread Name: {Thread.CurrentThread.Name}");
Console.WriteLine($"Daemon/Background Thread: {Thread.CurrentThread.IsBackground}");
}
}
Are you seeing any output at all from the console? If not you might be deadlocked waiting for the Console.ReadKey to finish before the threads can write to the console output stream. This is because Console.WriteLine and Console.ReadKey both obtain a lock to the same object.
The Console.WriteLine only obtains the lock the first time it outputs to the stream, so an easy way to test that is to add a Console.WriteLine before you do a ReadKey.
You're probably running into the maximum thread count of the default thread pool. It's the default thread pool that handles the Timer.
https://learn.microsoft.com/en-us/dotnet/standard/threading/the-managed-thread-pool
Thread.Sleep will block the thread and is usually a lazy way to get what you're really after. There are better scheduling methods that won't block or be as heavy-weight as a Thread.

C# time.sleep not working as expected for no apparent reason [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 3 years ago.
Improve this question
So this algorithm should flash the word finished in 1 second intervals 3 times but it just freezes for 5 seconds instead. Any ideas?
bool appear = false;
int i = 0;
while (i < 5)
{
i++;
if (appear == false)
{
appear = true;
Finished_label.Visible = true;
}
else
{
appear = false;
Finished_label.Visible = false;
}
System.Threading.Thread.Sleep(1000);
}
*Edit I am writing this in C# Visual Studio Windows Forms Application
Thread.Sleep() blocks the UI thread, so you don't see the changes. You could use
await Task.Delay(1000);

Time delays without using Thread.sleep() [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 6 years ago.
Improve this question
I wrote a client application where I am using two threads other than the main thread.The Background thread is used to receive data through TCP IP,while after receiving I am calling another thread that will show the received data continuously using a for loop.But after every iteration the for loop needs to wait for 30 seconds.I have used Thread.sleep(30000) but the dont know why its not working,sometimes it wakes up from sleep mode before 30 seconds.I am using dot net framework 4.Please suggest some other alternatives.
for(n=0;n<=m;n++)
{
//show data;
//wait for 30 seconds
}
Timers are not accurate in .NET . You might not get 30000 exactly.
You can using Thread.Sleep(30000); Or await Task.Delay(30000) but you need to mark your method as async;
The difference is that Thread.Sleep block the current thread, while Task.Delay doesn't.
public async Task MyMethod()
{
int n;
int m = 100;
for(n=0; n<=m; n++)
{
//show data;
//wait for 30 seconds
await Task.Delay(30000);
}
}
For .NET 4, you can use this alternative:
public static Task Delay(double milliseconds)
{
var tcs = new TaskCompletionSource<bool>();
System.Timers.Timer timer = new System.Timers.Timer();
timer.Elapsed += (obj, args) =>
{
tcs.TrySetResult(true);
};
timer.Interval = milliseconds;
timer.AutoReset = false;
timer.Start();
return tcs.Task;
}

How to create thread according to integer value? [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 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);
}
}

Best architecture to set a realtime logging window to write from different threads like output window in visualstudio [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I am designing an application and it runs different components each on a different thread. I need a way to report back to the user interface the state of those components and the tasks they complete and if any errors occurred. My first approach was to write from all the different components to a log file. And then I monitored that file for changes, to reload the changes in a text box (my output window). However I noticed that using file monitor does not perform very well, and it slows downs the component threads and their tasks. So I was thinking to create something like the output windows in vs2010, where they can log any data while debugging, it seems to be very efficient, and can hold a lot of data. Any ideas what would be the best approach? One important fact, is that there should be a way to communicate all the component threads with the logging output window, to display results, avoid collisions, etc. I am using .NET 4.0
I think you can just improve your idea with writing to the log file, just do it async, so you will not block the thread.
You can use something like NLog or log4net.
Well I don't see why you can't do something like in this example code (I must say that I consider that you are doing all the syncing and thread stopping, this is just a quick example of using Control.Invoke to make it thread safe, also you can use BeginInvoke and it won't block threads that are writing to the textBox):
List<Thread> threads = new List<Thread>();
bool closeThreads;
private void button1_Click(object sender, EventArgs e)
{
closeThreads = false;
for (int i = 1; i < 10; i++)
{
Thread t = new Thread(new ParameterizedThreadStart(ThreadMethod));
threads.Add(t);
t.Start(i);
}
}
private void button2_Click(object sender, EventArgs e)
{
closeThreads = true;
foreach (Thread t in threads)
{
if (t.ThreadState != ThreadState.Stopped)
t.Join(3);
}
}
delegate void textWriter(string textToWrite);
void WriteText(string textToWrite)
{
this.textBox1.AppendText(textToWrite);
}
void ThreadMethod(object i)
{
int threadNumber = (int)i;
int currentNumber = 100 * threadNumber;
Random rand = new Random(threadNumber);
while(!closeThreads)
{
currentNumber = (currentNumber + rand.Next(0,100))%1000;
Thread.Sleep(currentNumber);
//textBox1.Invoke(new textWriter(WriteText), new object[]{"Thread " + threadNumber.ToString() + " " + currentNumber.ToString() + Environment.NewLine});
//this won't block your threads
string text = "Thread " + threadNumber.ToString() + " " + currentNumber.ToString() + Environment.NewLine;
textBox1.BeginInvoke(new textWriter(WriteText), new object[]{text});
}
}
In order to try the code, you will need to make a form with two Buttons and one TextBox

Categories