Debug.WriteLine doesn't work on different threads [closed] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
var timer = new Timer
{
Enabled = true,
Interval = 500
};
Debug.WriteLine("new timer created");
timer.Elapsed += (s, e) =>
{
Debug.WriteLine("hello from timer");
// this doesn't get shown
// in the output window
}
What do I need to do to be able to see my last Debug.WriteLine() in the output window above?

You are actually not using separate threads, the System.Timers timer runs on the UI Message pump if it is available. If you have blocked the UI thread the timer will never run.
Check either that the UI thread is not blocked, use System.Threading.Timer that does not use the UI thread, or set SynchronizingObject to null so it will use a threadpool thread instead of the UI thread.
EDIT: Or like Hans said in his comment, you are running in the console and Main() is exiting before the timer has a chance to fire.

Related

How to write a Windows Service that has a long running function using async? [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 4 years ago.
Improve this question
My first non-async attempt was to use a timer to call the process every 15 seconds. This quickly created multiple processes running which started a race condition on the database because the function _myApp.ProcessQueue(); could take 5-10 minutes to run based on the size of the queue. This actually locked up the database because it was trying to read and write to the same rows. If I increase the timer it would prevent the potential for a race condition but I don't think that's a very pragmatic way to go about this service.
protected override void OnStart(string[] args)
{
_log.Info($"Service is started at {DateTime.Now}.");
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
timer.Interval = 15000;
timer.Enabled = true;
}
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
int recCount = _dbHandler.CheckQueueCount();
if (recCount > 0)
{
_log.Info($"Found {recCount} records in the queue.");
try
{
_myApp.ProcessQueue();
}
catch (Exception exception)
{
_log.Error(exception);
Stop();
}
}
}
I'm thinking the way to go about this is to use an asynchronous function but I'm having trouble getting that written since I haven't used .Net's async capabilities before.
Use the OnStart() to initialize your runner in an other thread (Task.Run() or if you have to tune some parameters Task.Factory.Start()) to have a proper return of the method within short time.
If I understand you correctly, you only want to process one job at a time and after that you want to process the next one, right?
My examples include always to wait for additional 15s. If you don't want this, you have to adjust the code a little bit.
Without async/await
To synchronize your loop with your job processing, you can start the job in another thread (see above) and use a AutoResetEvent. In your loop you gonna wait with _autoResetEvent.WaitOne() and as soon as your job has been done you can signal with _autoResetEvent.Set() the other thread to continue.
Use something appropriate to wait for the 15s like Thread.Sleep()
With async/await
It's much easier, you only have to await your task call.
await Task.Run(() => MyJobMethod(argA, argB, ...));
await Task.Delay(15000);

Is waiting a thread to be alive with a loop good practice? [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
Do we really have to do this?
// Loop until worker thread activates.
while (!workerThread.IsAlive);
Wouldn't it be better to just use a ManualResetEvent (or else) at the start of the thread's function?
Edit 1:
Perhaps in the MSDN example context it would be "appropiate":
// Start the worker thread.
workerThread.Start();
Console.WriteLine("main thread: Starting worker thread...");
 
// Loop until worker thread activates.
while (!workerThread.IsAlive);
Otherwise this just feels like an awful code smell.
Source: http://msdn.microsoft.com/en-US/library/7a2f3ay4(v=vs.80).aspx
Please ignore the MSDN example, it's horrible and senseless. In particular, the spin waiting on IsAlive makes no sense because there is no way for the thread to be terminated "before it has a chance to execute", as the MSDN says. The thread is free not to check the flag you set for requesting termination until it is ready. Spin-waiting on IsAlive never makes sense -- use Thread.Join() to wait on exit, and events (or monitors) to wait for other states.
Good practice is to use the Task-based Asynchronous Pattern (TAP)
Use Task.Run like this,
public async Task DoStuff(CancellationToken token)
{
await Task.Run(
() => Console.WriteLine("Stuff"),
token)
}
or just,
Task.Run(() => Console.WriteLine("Stuff")).Wait();
There is no built-in infrastructure to wait for thread to start, because in most cases this should not be important. We must wait for thread to finish always, but let it do about its business in the mean time.
You probably even don't want to wait for thread to start. You probably want for thread to activate some of its functionality, and in general case there could me more than one of those functionalities. No built-in system can cater for this, so you have to roll your own synchronization.
Just have some event that is created when the thread is created, but is raised in the thread run code. When you create and start the thread wait on this event and that's it.

I cannot use the form which I've opened from Timers.Timer event [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I am a beginner in C#.
My idea is to create an application which is checking remote web site and show some form if condition is true. So it checks every 10 second, it should works like a notifier.
I start a timer when start my application.
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
TimerEvent timer = new TimerEvent();
timer.startTimer();
Application.Run();
}
}
Then I open the form every 10 second.
class TimerEvent
{
public void startTimer()
{
System.Timers.Timer aTimer = new System.Timers.Timer();
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = 10000;
aTimer.Enabled = true;
}
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
Form1 form = new Form1();
form.Show();
}
}
It opens every 10 second new form, but I cannot use it.
I assuming that I missed something about threading.
Thanks in advance.
UPDATE
Solution for me C# open a new form, and close a form
You are using a System.Timers.Timer without using the SynchronizingObject property. That means you are calling Show() from a pool thread, it should not work at all (in Debug mode).
Also you are calling Application.Run() without specifying a MainForm.
The solution dpends on what you actually want to happen (a new Form per 10 seconds gets pretty messy quickly).
Use a normal MainForm and a Windows.Forms.Timer to pop up new Forms.
I assuming that I missed something about threading.
The main thing to know is that the UI is single-threaded by design. Use events, not threads.

Windows Service Startup (Timeout (30000 milliseconds)) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I have created a windows service Setup file for my project in vb.net,but after windows service installation when i am trying to start that windows service its throwing the following Error:
The service did not respond to the start or control request in a timely fashion.
Timeout (30000 milliseconds) waiting for the Test service to connect.
What can i do?
You're limited to a 30 second startup time in a windows service. If the service doesn't start responding to ServiceControlManager calls after 30 seconds, it gets terminated.
This generally happens because you've put some long running code in your OnStart() method which doesn't complete in a timely fashion.
Try to keep the bare minimum of code in your Service Constructor & OnStart methods and then anything else if needs to do such as calling the database, loading data, IO, calling external services etc, should be done in the main application.
Have a look at your service OnStart() method? Are you doing any heavy-lifting there? Not throwing exceptions if something taking longer than expected?
It looks as if you trying to do stuff like this
class MyService
{
public void OnStart()
{
//blocks here
Thread.Sleep(TimeSpan.FromSeconds(31));
}
}
Instead you should do something like
class MyService
{
private Thread workerThread;
public void OnStart()
{
workerThread = new Thread(()=>
{
Thread.Sleep(TimeSpan.FromSeconds(31));
})
// doesn't block here
workerThread.Start();
}
}

Is there a "Sleep" command? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
In a lot of languages, there's a
wait(milliseconds)
or
sleep(milliseconds)
command, that just makes your program not execute any more code until the sleep is up (this doesn't mean it stops the code that's running, it just pauses from running more. Is there a command like this in C#?
Thread.Sleep(time) doesn't work, it pauses all code that is currently executing as well (basically freezes your program)
Thread.Sleep(int milliseconds)
is what you're looking for
In C#, everything is running on one thread by default. If you want you can create another thread to run a specific piece of code. Then, you can sleep that thread so your app won't freeze.
Check this question out for more information: How do I run a simple bit of code in a new thread?
Yeap:
Thread.Sleep(milliseconds)
http://msdn.microsoft.com/es-es/library/system.threading.thread.sleep(v=vs.80).aspx
Yeah there is.
Thread.Sleep(milliseconds)
For example, if you use Thread.Sleep(5000) , it will make thread sleep for 5 seconds. Read more # MSDN
Thread.Sleep(milliseconds) should do it for you
You'll want to verify the syntax as I'm just wingin' it, but this will go into a non-blocking loop for the designated amount of time...
// Set the wait time
double waitTime = 5.0;
// Get the current time
DateTime start = DateTime.Now;
// Check the wait time
while(DateTime.Now.Subtract(start).TotalSeconds < waitTime)
{
// Keep the thread from blocking
Application.DoEvents();
}
That assumes you're using Windows Forms. If you're using WPF:
//Application.DoEvents();
this.Dispatcher.Invoke(DispatcherPriority.Background, new Action(() => { }));
Again, you'll want to verify the syntax first...

Categories