473,569 Members | 2,590 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

thread timing

Hi,

I don't understand why sometimes, a loop running in a thread takes
much more time than usual.
I have a thread that must call each 20 ms a C++ unmanaged function.
I made a C++ managed wrapper for calling this function from C# (see
below _serialChannel. ItTask ()).
It works great but for this timing problem.
Here below, the main loop for this thread :

while (true)
{
Util.TraceLine ("before WaitOne");
if (_itTaskEvent.W aitOne (25, false))
{
Util.TraceLine ("ItTaskProc end asked");
break;
}
Util.TraceLine ("after WaitOne");
Util.TraceLine ("before ItTaskProc");
_serialChannel. ItTask ();
Util.TraceLine ("after ItTaskProc");
progressBarItTa skThread.Perfor mStep ();
if (progressBarItT askThread.Value >= progressBarItTa skThread.Maximu m)
progressBarItTa skThread.Value = progressBarItTa skThread.Minimu m;

dtLast = dtCurrent;
dtCurrent = DateTime.Now;
Util.TraceLine ("dtCurrent= " + dtCurrent.ToStr ing ("HH:mm:ss:f ff: ")
+
", dtLast=" + dtLast.ToString ("HH:mm:ss:f ff: "));

TimeSpan diff = dtCurrent.Subtr act (dtLast);
if (_minItTaskElap sedTime > diff)
{
_minItTaskElaps edTime = diff;
Log ("New mininimum ItTaskElapsedTi me = " + _minItTaskElaps edTime);
}

if (_maxItTaskElap sedTime < diff)
{
_maxItTaskElaps edTime = diff;
Log ("New maximum ItTaskElapsedTi me = " + _maxItTaskElaps edTime);
}
}
Here is the log output :

09:14:06:546: ItTask thread: before WaitOne
09:14:06:578: ItTask thread: after WaitOne
09:14:06:578: ItTask thread: before ItTaskProc
09:14:06:578: ItTask thread: after ItTaskProc
09:14:06:578: ItTask thread: dtCurrent=09:14 :06:578: ,
dtLast=09:14:06 :546:
09:14:06:578: ItTask thread: before WaitOne
09:14:06:609: ItTask thread: after WaitOne
09:14:06:609: ItTask thread: before ItTaskProc
09:14:06:609: ItTask thread: after ItTaskProc
09:14:06:609: ItTask thread: dtCurrent=09:14 :06:609: ,
dtLast=09:14:06 :578:
09:14:06:609: ItTask thread: before WaitOne
09:14:06:640: ItTask thread: after WaitOne
09:14:06:640: ItTask thread: before ItTaskProc
09:14:06:656: ItTask thread: after ItTaskProc
09:14:06:656: ItTask thread: dtCurrent=09:14 :06:656: ,
dtLast=09:14:06 :609:
09:14:06:796: ItTask thread: before WaitOne
09:14:06:828: ItTask thread: after WaitOne
09:14:06:828: ItTask thread: before ItTaskProc
09:14:06:828: ItTask thread: after ItTaskProc
09:14:06:828: ItTask thread: dtCurrent=09:14 :06:828: ,
dtLast=09:14:06 :656:
09:14:06:828: ItTask thread: New maximum ItTaskElapsedTi me =
00:00:00.171875 0

As you can see, the loop runs usually in 30-40 ms but the last one run
in 171 ms !
I set priority for this thread to ThreadPriority. Highest.

Can anyone help me to understand this behaviour ?

Thanks in advance.

Regards,

Droopy.
Nov 16 '05 #1
7 2755
Don't ever assume that a task will end in a fixed amount of time, your
thread will NOT be on the CPU all the time, Windows is no hard real time OS.
For the same reason, don't assume you can call a function every x msec's.
Every thread in the system has a max. quantum (OS version dependent) to be
on the CPU, the scheduler will pre-empt and switch to another (higher
priority) thread. When there is no higher priority runable thread available,
the scheduler will scan the same priority list (in a round-robin fashion).
To prevent starvation, the scheduler can lower thread priorities and boost
the priority of others.

Willy.
"Droopy" <dr********@hot mail.com> wrote in message
news:ff******** *************** ***@posting.goo gle.com...
Hi,

I don't understand why sometimes, a loop running in a thread takes
much more time than usual.
I have a thread that must call each 20 ms a C++ unmanaged function.
I made a C++ managed wrapper for calling this function from C# (see
below _serialChannel. ItTask ()).
It works great but for this timing problem.
Here below, the main loop for this thread :

while (true)
{
Util.TraceLine ("before WaitOne");
if (_itTaskEvent.W aitOne (25, false))
{
Util.TraceLine ("ItTaskProc end asked");
break;
}
Util.TraceLine ("after WaitOne");
Util.TraceLine ("before ItTaskProc");
_serialChannel. ItTask ();
Util.TraceLine ("after ItTaskProc");
progressBarItTa skThread.Perfor mStep ();
if (progressBarItT askThread.Value >= progressBarItTa skThread.Maximu m)
progressBarItTa skThread.Value = progressBarItTa skThread.Minimu m;

dtLast = dtCurrent;
dtCurrent = DateTime.Now;
Util.TraceLine ("dtCurrent= " + dtCurrent.ToStr ing ("HH:mm:ss:f ff: ")
+
", dtLast=" + dtLast.ToString ("HH:mm:ss:f ff: "));

TimeSpan diff = dtCurrent.Subtr act (dtLast);
if (_minItTaskElap sedTime > diff)
{
_minItTaskElaps edTime = diff;
Log ("New mininimum ItTaskElapsedTi me = " + _minItTaskElaps edTime);
}

if (_maxItTaskElap sedTime < diff)
{
_maxItTaskElaps edTime = diff;
Log ("New maximum ItTaskElapsedTi me = " + _maxItTaskElaps edTime);
}
}
Here is the log output :

09:14:06:546: ItTask thread: before WaitOne
09:14:06:578: ItTask thread: after WaitOne
09:14:06:578: ItTask thread: before ItTaskProc
09:14:06:578: ItTask thread: after ItTaskProc
09:14:06:578: ItTask thread: dtCurrent=09:14 :06:578: ,
dtLast=09:14:06 :546:
09:14:06:578: ItTask thread: before WaitOne
09:14:06:609: ItTask thread: after WaitOne
09:14:06:609: ItTask thread: before ItTaskProc
09:14:06:609: ItTask thread: after ItTaskProc
09:14:06:609: ItTask thread: dtCurrent=09:14 :06:609: ,
dtLast=09:14:06 :578:
09:14:06:609: ItTask thread: before WaitOne
09:14:06:640: ItTask thread: after WaitOne
09:14:06:640: ItTask thread: before ItTaskProc
09:14:06:656: ItTask thread: after ItTaskProc
09:14:06:656: ItTask thread: dtCurrent=09:14 :06:656: ,
dtLast=09:14:06 :609:
09:14:06:796: ItTask thread: before WaitOne
09:14:06:828: ItTask thread: after WaitOne
09:14:06:828: ItTask thread: before ItTaskProc
09:14:06:828: ItTask thread: after ItTaskProc
09:14:06:828: ItTask thread: dtCurrent=09:14 :06:828: ,
dtLast=09:14:06 :656:
09:14:06:828: ItTask thread: New maximum ItTaskElapsedTi me =
00:00:00.171875 0

As you can see, the loop runs usually in 30-40 ms but the last one run
in 171 ms !
I set priority for this thread to ThreadPriority. Highest.

Can anyone help me to understand this behaviour ?

Thanks in advance.

Regards,

Droopy.

Nov 16 '05 #2
Thanks for the answer.
I understand of course that Windows is not a real time OS.
I don't really care when I call WaitOne with 20 or 25 ms timeout if it
takes 30 ms but I thought that 171 ms when an average time of 30-40 ms
was observed is not normal, even for a non real time OS !

Droopy.

Nov 16 '05 #3

<dr********@hot mail.com> wrote in message
news:11******** **************@ f14g2000cwb.goo glegroups.com.. .
Thanks for the answer.
I understand of course that Windows is not a real time OS.
I don't really care when I call WaitOne with 20 or 25 ms timeout if it
takes 30 ms but I thought that 171 ms when an average time of 30-40 ms
was observed is not normal, even for a non real time OS !


That depends on the number of runable threads waiting to be scheduled,
because of the "little game" you play by setting your thread priority to
'highest' possible, you are delaying the scheduling of lower priority theads
untils the scheduler decides that your game must end and he boost the
(dynamic) priority of the other runable threads and lowers your threads
(dynamic) priority. In general you better off running your threads with
normal priority this way you don't disturb the scheduler job (and not to
forget the GC and Finalizers job in a managed application).

Willy.

Nov 16 '05 #4
I tried setting thread priority to Normal, then it takes more than 200
ms.
Anyway, thanks for your answers.

Droopy.

Nov 16 '05 #5

I don't known what is actualy done in "_serialChannel .ItTask ();" and
"progressBarItT askThread.Perfo rmStep ();" also I 'm not sure this is a
Windows Forms application but I guess so.
Also I'm not clear how you log your messages but supposed you are writing
them to disk, there's a chance your thread is waiting for IO rundown when
flushing the buffer.
Therefore I've written a small console application using the same algorithm
as the one you posted, but here I'm writing debug messages to the debugger
output.
When I ran this the average remains at 30 msec. with a single max. of
50msec. early in the process, this without running other CPU intensive
tasks.

#define DEBUG
using System;
using System.Threadin g;
using System.Diagnost ics;

namespace Willys
{
class Tester
{
static AutoResetEvent _itTaskEvent = new AutoResetEvent( false);

static void Main()
{
string debString;
TimeSpan _minItTaskElaps edTime;
TimeSpan _maxItTaskElaps edTime;
DateTime dtCurrent;
DateTime dtLast;
bool firstRun = true;;
while (true)
{
Debug.WriteLine ("before WaitOne");
if (_itTaskEvent.W aitOne (25, false))
{
Debug.WriteLine ("ItTaskProc end asked");
break;
}
Debug.WriteLine ("after WaitOne");
Debug.WriteLine ("before ItTaskProc");
// Call empty method
ItTask ();
Debug.WriteLine ("after ItTaskProc");
// progressBarItTa skThread.Perfor mStep ();
// if (progressBarItT askThread.Value >= progressBarItTa skThread.Maximu m)
// progressBarItTa skThread.Value = progressBarItTa skThread.Minimu m;

dtLast = dtCurrent;
dtCurrent = DateTime.Now;
debString = String.Format(" dtCurrent= {0}: , dtLast= {1} )",
dtCurrent.ToStr ing("HH:mm:ss:f ff"),
dtLast.ToString ("HH:mm:ss:fff" ) );
Debug.WriteLine (debString);

TimeSpan diff = dtCurrent.Subtr act (dtLast);
if (_minItTaskElap sedTime > diff)
{
_minItTaskElaps edTime = diff;
debString = String.Format(" New mininimum ItTaskElapsedTi me = {0} "
,_minItTaskElap sedTime);
Debug.WriteLine (debString);
}

if ((_maxItTaskEla psedTime < diff) && !firstRun)
{
_maxItTaskElaps edTime = diff;
debString = String.Format(" New maximum ItTaskElapsedTi me = {0}
",_maxItTaskEla psedTime);
Debug.WriteLine (debString);
}
else if (firstRun)
{
firstRun = false;
}
}
}
static void ItTask ()
{ return;}
}
}

WIlly.

<dr********@hot mail.com> wrote in message
news:11******** **************@ f14g2000cwb.goo glegroups.com.. .
I tried setting thread priority to Normal, then it takes more than 200
ms.
Anyway, thanks for your answers.

Droopy.

Nov 16 '05 #6
"_serialChannel .ItTask ();" is a wrapper to an unmanaged C++ function
that is handling a serial port.
Yes it is a Windows Forms application and
"progressBarItT askThread.Perfo rmStep ();" is a ProgressBar used to
signal that the thread is running.
Here below is the code that log messages :

public class Util
{
// lock (typeof (Util)) does not seem to work
private static object forLocking = new object ();

public static void TraceLine (string message)
{
lock (forLocking)
{
Debug.WriteLine
(DateTime.Now.T oString ("HH:mm:ss:f ff: ") +
System.Threadin g.Thread.Curren tThread.Name +
": " + message);
}
}
}

At first, I thought that the call to unmanaged code was the source of
my problem but if you take a close look to my logs, you will see that
the time is not "lost" in calling "_serialChannel .ItTask ();" but it is
"lost" between the end of the loop (log for "dtCurrent" and "dtLast ")
and the begin of the loop (log for "before WaitOne") !
Again, thanks for you time,

Pierre.

Nov 16 '05 #7
Anyway, this is not a blocking problem for me.
I now really have a problem because I can "freeze" the "ItTask" thread.
When this thread is frozen, the serial port protocol generate a "link
down".

My application is listening for command from clients on a TCP port in
other threads (see code here below) :

....
client.BeginRec eive (state.buffer, 0, StateObject.Buf ferSize, 0,
new AsyncCallback (ReadCallback), state);
}

public void ReadCallback (IAsyncResult ar)
{
// Retrieve the state object and the handler socket
// from the asynchronous state object.
StateObject state = (StateObject) ar.AsyncState;
Socket handler = state.clientSoc ket;
Util.TraceLine ("Tcp:ReadCallb ack: Receiving from client = " +
handler.RemoteE ndPoint.ToStrin g () + " ...");

try
{
// Read data from the client socket.
int bytesRead = handler.EndRece ive (ar);
....

I have some connections opened (main channel + unsollicited channel +
client channel).
When the client closes, it closes all its connections and everything is
OK.
I tried to simulate a "crash" in the client by stopping it (via the
menu Debug->Stop Debugging) to force it not to close its connections.
My application catches a "Sockets.Socket Exception" for each connection
that is interrupted.
At this moment, my "ItTask" thread is frozen more than 3 seconds for 3
connections opened with client (see logs here below).
It automatically continue when these exceptions are "handled".

15:23:12:281: ItTask thread: before WaitOne
15:23:12:281: : Tcp:ReadCallbac k: Receiving from client =
127.0.0.1:2943 ...
15:23:15:687: ItTask thread: after WaitOne
15:23:15:687: ItTask thread: before ItTaskProc
15:23:15:687: ItTask thread: UMTrspPort::vLi nkDown called
15:23:15:718: ItTask thread: TrspPortManaged ::vCommEvent: LinkDown
15:23:15:687: : Tcp:ReadCallbac k: Receiving from client =
127.0.0.1:2944 ...
15:23:15:718: : ReadCallback: Exception catched:
System.Net.Sock ets.SocketExcep tion: Une connexion existante a dû être
fermée par l'hôte distant
at System.Net.Sock ets.Socket.EndR eceive(IAsyncRe sult asyncResult)
at IPRManaged.Tcp. ReadCallback(IA syncResult ar) in
c:\projects\ipr managed\iprmana ged\tcp.cs:line 165
15:23:15:750: ItTask thread: SerialChannel:: TransportCommEv ent:
CommEventType LinkDown received
15:23:15:750: : ReadCallback: handling finished for client =
127.0.0.1:2943 on 127.0.0.1:1414
15:23:15:765: IprSocket #33 read thread: ReadTcpSocket Exception
catched System.Net.Sock ets.SocketExcep tion: Une connexion existante a
dû être fermée par l'hôte distant
at System.Net.Sock ets.Socket.Rece ive(Byte[] buffer, Int32 offset,
Int32 size, SocketFlags socketFlags)
at System.Net.Sock ets.Socket.Rece ive(Byte[] buffer)
at IPRManaged.IprS ocket.ReadTcpSo cket() in
c:\projects\ipr managed\iprmana ged\iprsocket.c s:line 164
15:23:15:765: ItTask thread: SerialChannel:: TransportCommEv ent: event
queued, #1 items in queue
15:23:15:765: Serial Event: HandleSerialEve ntProc: handling LinkDown
event
15:23:15:765: Serial Event: FormMain::Handl eEvent: CommEventType
LinkDown received
15:23:15:781: ItTask thread: after ItTaskProc
15:23:15:781: IprSocket #33 read thread: ReadTcpSocket thread finished,
IprSocket #33 on 127.0.0.1:2945, remote host #1, remote socket #1,
connected = True, running = False, listener = False
The thread 'IprSocket #33 read thread' (0xc28) has exited with code 0
(0x0).
15:23:15:781: : ReadCallback: Exception catched:
System.Net.Sock ets.SocketExcep tion: Une connexion existante a dû être
fermée par l'hôte distant
at System.Net.Sock ets.Socket.EndR eceive(IAsyncRe sult asyncResult)
at IPRManaged.Tcp. ReadCallback(IA syncResult ar) in
c:\projects\ipr managed\iprmana ged\tcp.cs:line 165
15:23:15:796: ItTask thread: dtCurrent=15:23 :15:781: ,
dtLast=15:23:12 :281:
15:23:15:796: ItTask thread: New maximum ItTaskElapsedTi me =
00:00:03.500000 0
15:23:15:796: Serial Event: LinkDown, stopping Timecode thread

I hope I am clear enough, feel free to ask for more code or more
explanations.

So my question is :

Why is my ItTask frozen, it has nothing to do with socket handling ?
Thanks in advance,

Droopy

Nov 16 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
2248
by: Jeff | last post by:
I am running a worker thread that manipulates some hardware setting every so often. My problem is that the hardware manipulation cannot be interrupted once it has started How can I ensure that the entire operation will run to completion even when the ThreadAbortException is thrown Thanks Jeff
20
3465
by: Sacha | last post by:
Consider I have a working thread like this, while (1) { if ( g_pObject ) g_pObject->DoOneStep(); } with an class hierarchie like this
16
3292
by: droopytoon | last post by:
Hi, I start a new thread (previous one was "thread timing") because I have isolated my problem. It has nothing to do with calling unmanaged C++ code (I removed it in a test application). I have a thread "_itTaskThread" running. The application is listening on a TCP port. It accepts 2 connection from a client. I simulate a crash on the...
2
10514
by: Asad Khan | last post by:
I call the following method from my main form method: uploadThread = new Thread(new ThreadStart (this.doFTPUpload)); uploadThread.Name = "FTP Upload"; uploadThread.Start(); bool threadTerminatedGood = uploadThread.Join(client.transmissionTimeout*60*1000); if (!threadTerminatedGood) { throw new Exception("The upload thread was interrupted...
3
1688
by: gregory_may | last post by:
I have an application where I am using a System Thread to capture the screen & Broadcast it to clients. Its "working", but the timing on the background thread gets wildly erratic at times. Some times, its right away, some times after 10 seconds. I have included the setup of the process and the outline of the Call Back Method. As posted,...
13
11261
by: LordHog | last post by:
Hello all, I have a little application that needs to poll a device (CAN communications) every 10 to 15 ms otherwise the hardware buffer might overflow when there are message burst on the bus. I would implement an interrupt driven model, but the external device (which is connected via USB) does not support interrupts therefore the device...
7
7257
by: Boki | last post by:
Multi-thread read/write to a single file. I have two processing threads, thread A and thread B; and I called my queue as Q. Thread A will feed data into Q by user input, the timing is random. Thread B will read data from Q to process; this processing will communicate with a website. I think the best Q architecture is ring buffer as...
9
3977
by: Jon Slaughter | last post by:
I'm using Thread and ThreadStart to create a thread for testing purposes and I do not want to use a pool because the thread exists for the life time of the app. Eventually I might move on to using pools but at this point I'm just testing some timing issues. in any cause the thread is simply a counter, static void counter()
11
3754
by: Jon Slaughter | last post by:
Is there any way to start a terminated thread without using a pool or creating a new thread object? void counter() { clicks = 0; clock.Start(); while (counterActive) { clicks++;
0
7701
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7924
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8130
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7677
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7979
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5219
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
1
2115
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1223
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
940
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.