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;
}
Related
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.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I've been working on a timer in c# just to mess around since I've never done it before. I wanted to have the OnTimedEvents method I was declaring in a separate class as I will be calling it in various other classes for various other tests, but I cannot invoke it properly without getting errors. Specifically, I am getting No Overload Method for Method '' Takes 0 Arguments. I cannot work around this as I have with other methods. This is the code:
class MSOfficeApps {
public static Timer aTimer;
public void appWord() {
var programCS = new Program();
Microsoft.Office.Interop.Word.Application WordObj;
WordObj = (Microsoft.Office.Interop.Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
for(int i = 0; i < WordObj.Windows.Count; i++) {
object idx = i + 1;
Microsoft.Office.Interop.Word.Window WinObj = WordObj.Windows.get_Item(ref idx);
Console.WriteLine(WinObj.Document.FullName);
aTimer = new System.Timers.Timer(600000); //Sets timer to 6 minute increments
aTimer.Elapsed += ElapsedEventHandler(programCS.OnTimedEvent()); //Throwing an error at programCS.OnTimedEvent()
}
}
And this is what I'm trying to call
class Program {
private static void Main(string[] args) {
SearchProcesses sP = new SearchProcesses();
sP.BuildProcessLists();
Console.WriteLine("Press Enter to exit the program...");
Console.ReadLine();
}
public static void OnTimedEvent(Object source, ElapsedEventArgs e) {
Console.WriteLine("Event was raised at {0}", e.SignalTime);
}
}
Please advise :)
Change
aTimer.Elapsed += ElapsedEventHandler(programCS.OnTimedEvent());
to
aTimer.Elapsed += ElapsedEventHandler(programCS.OnTimedEvent);
You are invoking programCS.OnTimedEvent, rather than passing it as a reference (and invoking it without arguments), thus the error.
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
How to execute the multiple timers in different time interval using window scheduler....?
Is it possible using this functionality in .net...?
Thanks
You can also use single timer for different time intervals
for example:
private void Form_Load()
{
timer1.Interval = 1000; // 1 second
timer1.Start(); // Start timer, This will raise Tick event after 1 second
OnTick(); // So, call Tick event explicitly when we start timer
}
Int32 counter = 0;
private void timer1_Tick(object sender, EventArgs e)
{
OnTick();
}
private void OnTick()
{
if (counter % 1 == 0)
{
OnOneSecond();//Write your code in this method for one second
}
if (counter % 2 == 0)
{
OnTwoSecond();
}
counter++;
}
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
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
what is another command for 'Goto' ? I am using VSTO to make a ribbon for excel and is doesnt seem to support Goto, and I am trying to create a loop.
Edit: This is the loop i am trying to create :
TimeSpan startTimeSpan = new TimeSpan(0, 0, 0, 20);
TimeSpan timeDecrease = TimeSpan.FromSeconds(1);
private Timer timer = new Timer();
public void Ribbon_Load(Office.IRibbonUI ribbonUI)
{
timer.Interval = 1000;
this.ribbon = ribbonUI;
timer.Tick += timer_Tick;
timer.Start();
}
private void timer_Tick(object sender, EventArgs e)
{
if (startTimeSpan.ToString() != "00:00:00")
{
startTimeSpan = startTimeSpan - timeDecrease;
ribbon.InvalidateControl("timerLabel");
}
else
{
//when timer drop to "00:00:00" then loop to "TimeSpan startTimeSpan = new TimeSpan(0, 0, 0, 20);"
}
}
You probably want to be using a while loop, with the exit condition in the while statement, and use break to quit the loop before the exit condition is reached, or continue to skip the current iteration of the loop and go on to the next.
C# does support goto command, but it isn't for looping. Jump statements are very often not the best solution.
goto - http://msdn.microsoft.com/en-us/library/13940fs2.aspx
If you are trying to loop just use a looping statement.
looping - http://msdn.microsoft.com/en-us/library/ms228598(v=vs.90).aspx
You can find a lot of q&a on excel VSTO.
Whats wrong with something like:
for (int i = selectedRange.Rows.Count; i > 0; i--)
{
---YOUR CODE HERE---
}
OR
foreach (Excel.Range row in rng.Areas[1].Rows)
{
---YOUR CODE HERE---
}