Ticks are inconsistent and are fluctuating - vb.net

I have a sub and a button. And the code is like this:
Private Sub plus(ByRef a As Integer)
For i = 0 To a
a = a + a
Next
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim i As Integer = 19
Dim sw As New Stopwatch
sw.Start()
plus(i)
sw.Stop()
MsgBox(sw.ElapsedTicks)
End Sub
when I run the sub is by clicking the "button1" the program to output 310 thats means 310 is sw.elapsedticks
When I run the sub again by clicking the "button1" again, the program to output 1 << JUST ONE ellapsedticks
How can it be like that ?
I tried to stop my vb.net program and I run it again, and then I click its button again, it happened the same, which is worth 272 stopwatch elapsedticks then after I click again stopwatch , elapsedticks instead be 1 again
Please explain why it could happen?

The StopWatch class will fallback to using DateTime class and uses ticks for the measurements if your hardware doesn't support high-performance counter. Most computer's now day's, at least from Windows 2000 and later, have high-performance counters. With this in mind, the .NET Stopwatch class is based on this high frequency timer. In general, calling Start queries the performance counter and stores the value. When you Stop, it queries the performance counter again. Then the elapsed time is a simple subtraction of those two values to give you your ElapsedTicks.
Here are a few items to have a look at for further explanation...
This property just makes a call to GetRawElapsedTicks()
public long ElapsedTicks {
get { return GetRawElapsedTicks(); }
}
The below function returns the actual time that has elapsed from the time the stopwatch was started to when the stopwatch Stop method was called. As mentioned above, the elapsed time is a simple subtraction of those two values you can see that below: currentTimeStamp - startTimeStamp.
// Get the elapsed ticks.
#if FEATURE_NETCORE
public long GetRawElapsedTicks() {
#else
private long GetRawElapsedTicks() {
#endif
long timeElapsed = elapsed;
if( isRunning) {
// If the StopWatch is running, add elapsed time since
// the Stopwatch is started last time.
long currentTimeStamp = GetTimestamp();
long elapsedUntilNow = currentTimeStamp - startTimeStamp;
timeElapsed += elapsedUntilNow;
}
return timeElapsed;
}
Above you may notice the #if FEATURE_NETCORE and wonder what it is. These are called preprocessor commands. Basically they work like if-else statements except that if the condition isn't met it will not include the code at compile time as it's a pre-compile decision and not runtime...
With this all said, it was mentioned above already by Hans Passant about just in time (JIT) compiling. All of this I mentioned above breaks this down further for explanation. The real reason for the difference is the time it is taking for it to compile and run the first time.
Another thing to mention. The stopwatch class uses a long variable type to store what they call frequency. Frequency" stores the frequency of the high-resolution performance counter if one exists, otherwise it will store TicksPerSecond. The frequency cannot change while the system is running, so it's only initialized once.
Below are other constants that have a great deal with frequency and how it's calculated as well.
private const long TicksPerMillisecond = 10000;
private const long TicksPerSecond = TicksPerMillisecond * 1000;
When you create a new instance of the StopWatch class this is what is ran.
bool succeeded = SafeNativeMethods.QueryPerformanceFrequency(out Frequency);
if(!succeeded) {
IsHighResolution = false;
Frequency = TicksPerSecond;
tickFrequency = 1;
}
else {
IsHighResolution = true;
tickFrequency = TicksPerSecond;
tickFrequency /= Frequency;
}
Frequency as you can now see , has a big role in setting up how the elapsed time is going to be calculated and how often the tick is going to occur. Even when you stop your application it doesn't matter as the frequency is stored at this time. The only way to reset the frequency is to reboot your machine.

Related

WriteWithoutResponse WriteRequested event raised out of sequence on Windows.Devices.Bluetooth UWP GattLocalCharacteristic

With a BLE GattLocalService on Windows.Devices.Bluetooth while acting as the Peripheral with a characteristic with only a WriteWithoutResponse property and Plain protection level we are seeing GattLocalCharacteristic event WriteRequested is raised out of order as compared to the bytes being sent. We must only use the WriteWithoutResponse property on the characteristic and cannot use Notify, which seems to work fine. The trouble comes that we are sending around 10K over BLE with an MTU of 20 through this characteristic and need to reassemble them in order once all bytes are received. While many of the functions are asynchronous we can't seem to determine the order in which the bytes were originally sent. When this is setup on either Android or iOS this it works perfectly fine but on the UWP implementation we are notified out of order. Understandably, UWP is using several Async functions - but not being able to reassemble the bytes in the order received is quite problematic.
While researching Microsoft's github examples they only show receiving about 4 bytes on a single characteristic - order here wouldn't really matter. We have looked at using the Offset property on the GattWriteRequest, which appears to always be 0. We have monitored the calls to the GattLocalCharacteristic and determined they are notified out of order.
We've attempted to adapt from Microsoft's example here: https://learn.microsoft.com/en-us/windows/uwp/devices-sensors/gatt-server#write
Our vb.NET adaptation of this prior example:
Private Async Sub InitializePerihperal()
Dim serviceResult As GattServiceProviderResult = Await GattServiceProvider.CreateAsync(New Guid(peripheralServiceUUID))
If serviceResult.Error <> BluetoothError.Success Then
peripheralResponseReceived = True
peripheralResponseError = "GattServiceError"
Exit Sub
End If
serviceProvider = serviceResult.ServiceProvider
Dim characResult As GattLocalCharacteristicResult
Dim propCentralToPeripheral As New GattLocalCharacteristicParameters
propCentralToPeripheral.CharacteristicProperties = GattCharacteristicProperties.WriteWithoutResponse
propCentralToPeripheral.WriteProtectionLevel = GattProtectionLevel.Plain
characResult = Await serviceProvider.Service.CreateCharacteristicAsync(New Guid(CentralToPeripheralUUID), propCentralToPeripheral)
characCentralToPeripheral = characResult.Characteristic
End Sub
Private Async Sub CentralResponseReceived(sender As GattLocalCharacteristic, args As GattWriteRequestedEventArgs) Handles characCentralToPeripheral.WriteRequested
Dim sequence As Int32 = Threading.Interlocked.Increment(PerihperalWriteSequence)
Using requestDeferral As Windows.Foundation.Deferral = args.GetDeferral
Dim request As GattWriteRequest = Await args.GetRequestAsync
Dim requestReader As DataReader = DataReader.FromBuffer(request.Value)
Dim response(CType(requestReader.UnconsumedBufferLength - 1, Int32)) As Byte
requestReader.ReadBytes(response)
'peripheralBlocks is a global ConcurrentDictionary
peripheralBlocks(sequence) = response
requestDeferral.Complete()
End Using
End Sub
We might be missing something, but it seems like either Offset on the response or the function should be called in sequence. Above we have attempted to eliminate issues with GetRequestAsync delays by immediately capturing a call sequence. Maybe we are just missing something on the API - but we can't seem to find anything.

avoid list view selected index changed firing twice

Quite a simple question, when the selected index of a list view is changed, the event fires twice, once for deselection and a second time to select the next item.
I need to use the event when selecting or deselecting at different times however whan deselecting only to reselect a moment later it makes half my ui flash from enabled being on to off and back on again, it also causes a fair bit of code to run so I just need a way of avoiding the deselection firing if it was another item that was clicked and not blank space (for deselection)
Dave R said to use a 100ms timer here : Am I missing something with my ListView selection event handling
which sounds like it would work but seems quite untidy or generally a bad way of doing it.
My only other idea was to use the click event and then find the item at the location? but I'd rather not go to the hassle
thanks in advance!
-EDIT-
I've just thought that the click event would fire first so I could set a flag that skips selection index changed code if the click event happened on an item and then resets the flag after it's been used therefore skipping the deselection? I'll have a look now but again doesnt feel like a very efficient or easy way of doing something that sounds quite simple?
Use the ItemSelectionChanged event instead - the ListViewItemSelectionChangedEventArgs can tell you which item caused it to fire, and whether it's selected or not.
i just tried another solution which is potentially without any delay, it worked for me:
If ListView1.Items(ListView1.FocusedItem.Index).Selected = False Then
'This is the deselected value
MsgBox("Deselected: " & ListView1.Items(ListView1.FocusedItem.Index).SubItems(0).Text)
Else
'This is the new selected value
MsgBox("Selected: " & ListView1.Items(ListView1.FocusedItem.Index).SubItems(0).Text)
End If
The following solution works even with a delay of 1 ms. To be sure it works probably you can choose a higher delay, 10 ms for example, but a delay of 100 ms will make it a bit laggy on selecting "nothing". Here's the C#-Code:
public class FixedListView : ListView
{
private Timer _ItemSelectionChangedTimer = new Timer();
private Timer _SelectedIndexChangedTimer = new Timer();
private ListViewItemSelectionChangedEventArgs _ItemSelectionChangedEventArgs;
private EventArgs _SelectedIndexChangedEventArgs;
public FixedListView()
{
this._ItemSelectionChangedTimer.Interval = 1;
this._SelectedIndexChangedTimer.Interval = 1;
this._ItemSelectionChangedTimer.Tick += (sender, e) =>
{
this.OnItemSelectionChanged(this._ItemSelectionChangedEventArgs);
this._ItemSelectionChangedEventArgs = null;
};
this._SelectedIndexChangedTimer.Tick += (sender, e) =>
{
this.OnSelectedIndexChanged(this._SelectedIndexChangedEventArgs);
this._SelectedIndexChangedEventArgs = null;
};
}
protected override void OnItemSelectionChanged(ListViewItemSelectionChangedEventArgs e)
{
if (this._ItemSelectionChangedTimer.Enabled)
{
this._ItemSelectionChangedTimer.Stop();
base.OnItemSelectionChanged(e);
}
else
{
this._ItemSelectionChangedEventArgs = e;
this._ItemSelectionChangedTimer.Start();
}
}
protected override void OnSelectedIndexChanged(EventArgs e)
{
if (this._SelectedIndexChangedTimer.Enabled)
{
this._SelectedIndexChangedTimer.Stop();
base.OnSelectedIndexChanged(e);
}
else
{
this._SelectedIndexChangedEventArgs = e;
this._SelectedIndexChangedTimer.Start();
}
}
}
And here is the VB-Code:
Public Class FixedListBox
Inherits ListView
Public Sub New()
Me._ItemSelectionChangedTimer.Interval = 1
Me._SelectedIndexChangedTimer.Interval = 1
AddHandler Me._ItemSelectionChangedTimer.Tick, _
Sub(sender, e)
Me.OnItemSelectionChanged(Me._ItemSelectionChangedEventArgs)
Me._ItemSelectionChangedEventArgs = Nothing
End Sub
AddHandler Me._SelectedIndexChangedTimer.Tick, _
Sub(sender, e)
Me.OnSelectedIndexChanged(Me._SelectedIndexChangedEventArgs)
Me._SelectedIndexChangedEventArgs = Nothing
End Sub
End Sub
Private _ItemSelectionChangedTimer As New Timer()
Private _SelectedIndexChangedTimer As New Timer()
Private _ItemSelectionChangedEventArgs As ListViewItemSelectionChangedEventArgs
Private _SelectedIndexChangedEventArgs As EventArgs
Protected Overrides Sub OnItemSelectionChanged(e As ListViewItemSelectionChangedEventArgs)
If Me._ItemSelectionChangedTimer.Enabled Then
Me._ItemSelectionChangedTimer.Stop()
MyBase.OnItemSelectionChanged(e)
Else
Me._ItemSelectionChangedEventArgs = e
Me._ItemSelectionChangedTimer.Start()
End If
End Sub
Protected Overrides Sub OnSelectedIndexChanged(e As EventArgs)
If Me._SelectedIndexChangedTimer.Enabled Then
Me._SelectedIndexChangedTimer.Stop()
MyBase.OnSelectedIndexChanged(e)
Else
Me._SelectedIndexChangedEventArgs = e
Me._SelectedIndexChangedTimer.Start()
End If
End Sub
End Class
You can use the control like a normal ListView but SelectedIndexChanged and ItemSelectionChanged will fire only once.
Have fun...
Just check in the SelectedIndexChanged event whether the focused item is null and exit.
ListView^ item = listView1-> FocusedItem; //get selected item
if (item == nullptr){return;) // this line exits when deselection event fires
String^ data1 = Convert::ToString ( item-> SubItems [0] ); // get your data from columns like so
MessageBox::Show (data1); // display
note that you could grab data under several columns by changing index provided in SubItems
And using timers and delays will just incur overhead especially with large databases causing your application to slow Code in visual C++ .NET but the same theory applies for C# and others
Enjoy!!

Setting up a 'Timeout' feature in windows forms app

Dows anyone know how I can build a timeout feature into a windows forms app.
The app is event driven, but I am thinking of somehow using a timer which counts down for say 10minutes, and one the timer ticks then we time out the user.
The problem I have is how can I reset the timer each time the mouse is moved or clicked.
Any help appreciated.
Cheers
you can use System.Windows.Forms.Timer.
you can drag it from your toolbox to the designer surface.
Use the properties window to set the Interval Property to the time span you want(miliseconds), the Enabled property should be set to false.
on the for load set the timer Enabled property to true.
(The event handler in the sample are written using c# - sorry about that)
private void Form1_Load(object sender, EventArgs e)
{
timer1.Enabled = true;
}
Double click the timer tick event to register to the event, and close the form on the timer tick
private void timer1_Tick(object sender, EventArgs e)
{
Close();
}
In setting timer.Interval to 0 it does not work ?
Private Sub Form1_MouseMove(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseMove
Me.Timer1.Stop()
Me.Timer1.Start()
End Sub
As bad as it seems, I think the best way for that is to use a system.timer object with a set interval of a few milliseconds at most.
What I saw once is the use of a global variable that would get the time of the last action and that variable would be set to Now (using a global function for example) each time an action is performed. In your timer elapsed event, you check if now if bigger that the last action with your 10 minutes limit and act accordingly.
As for multi-form app, you could either use a different timer on each form , or only have the timer run on your main form.
Hope that helps.

.NET multi-threaded variable access

I have an application with 4 threads. (GUI, Controller, Producer, Consumer)
The GUI is self-explanatory.
The controller starts the producer and consumer threads after some intial setup.
The producer creates items and places them in a free slot in a "ring buffer"
The consumer takes items from the "ring buffer" and writes them to disk.
The producer creates items at a much higher rate than the consumer.
The consumer is IO heavy and IO bound.
Currently I am checking a variable in each ring buffer slot to determine if it can be written to.
if Slot.Free then
Write Slot.Data To Disk
end if
I am not using lock/synclock instead I'm just reading / writing the value of the slot's "free" variable. I don't believe that is correct even though it is a volatile read/write. Is there a better method to read/write this variable? The variable is of type "integer" and is either 0 or 1.
You mention using a ring buffer, but a (properly implemented) ring buffer would be able to determine if it's full without checking all it's elements, eliminating the need for a boolean in each slot.
I'm not used to VB.NET, but this should be a working (if crude) implementation of a ring buffer that blocks when it's full / empty on respective write / read actions.
Friend Class RingBuffer(Of T)
Private _slots() As T
Private _head As Integer
Private _tail As Integer
Private _readableSlots As Semaphore
Private _readLock As Object
Private _writableSlots As Semaphore
Private _writeLock As Object
Public Sub New(ByVal size As Integer)
ReDim _slots(size - 1)
_head = 0
_tail = 0
_readLock = New Object
_writeLock = New Object
_readableSlots = New Semaphore(0, size)
_writableSlots = New Semaphore(size, size)
End Sub
Public Function Dequeue() As T
Dim item As T
_readableSlots.WaitOne()
SyncLock _readLock
item = _slots(_head)
_head = (_head + 1) Mod _slots.Length
End SyncLock
_writableSlots.Release()
Return item
End Function
Public Sub Enqueue(ByVal item As T)
_writableSlots.WaitOne()
SyncLock _writeLock
_slots(_tail) = item
_tail = (_tail + 1) Mod _slots.Length
End SyncLock
_readableSlots.Release()
End Sub
End Class
Once you have that, your Producer and Consumer can be really dumb :) It's not exactly guaranteed that items are processed in-order if you have multiple consumers however:
Private _buffer As RingBuffer(Of Integer) = New RingBuffer(Of Integer)(5)
Private Sub Producer()
Dim i As Integer = 0
Do While True
_buffer.Enqueue(i)
i = i + 1
Loop
End Sub
Private Sub Consumer()
Do While True
Debug.WriteLine(("Consumer A: " & _buffer.Dequeue))
Thread.Sleep(1000)
Loop
End Sub
There are several ways you can do this safely.
If your architecture and requirements allow it, you can use custom events so one thread can simply signal a different listening thread to notify that a variables state has been changed. You do have to keep track of who is consuming what events though, and if those consumers are read-only on the variable, or read/write.
You can also use a simple custom wrapper class around a variable type (or use a generic) that does the lock/unlock code for you. In VB.NET, I've found that using the Monitor class to lock the private instance variable is really handy.
Mutexes and semaphores - .NET has a Mutex class and a Semaphore class. These both assist in controlling access to thread-shared variables. I like Mutexes because they're so easy to use, and you don't need to keep track of how many threads might have access to a given resource.
Please DO note that although some MSDN documentation claims that reading to or writing from a value-type (Integer, Double, etc) is an atomic operation, and hence "thread-safe", this is SELDOM TRUE in actual VB code. A simple statement like X = Y is NOT in fact atomic, as it you have to perform two operations here - first, loading the value of Y, and then setting the value of X. Little things like this make me lose my hair :)
Whatever method you decide to roll with, I find that liberal commenting throughout your code describing who has access to what resources at what time is invaluable - three months from now, you're not gonna remember the fine points of this code and comments really help.
Best of luck!
You could use Semaphores to solve the Producer Consumer problem:
static void Main(string[] args)
{ new Thread(Producer).Start(); new Thread(Consumer).Start(); }
static int K = 10;
static n = new Semaphore(0, K), e = new Semaphore(K, K);
static int[] buffer = new int[K];
static int _in, _out;
static void Producer()
{
while (true)
{
e.WaitOne();
buffer[_in] = produce();
_in = (_in + 1) % buffer.Length;
n.Release();
}
}
static void Consumer()
{
while (true)
{
n.WaitOne();
var v = buffer[_out];
_out = (_out + 1) % buffer.Length;
e.Release();
consume(v);
}
}
Any time that data can be accessed by more than one thread, you have to write your code to assume that it will be accessed by more than one thread. "Murphy's Law" rules multithreaded scenarios.
For instance, if one thread is filling a slot, and the other is emptying it, you need a lock around it.
You can make your checks interlocked operations and eliminate any concern:
const FREE = 0;
const FILLING = 1;
const READY = 2;
const DRAINIG = 3;
Producer:
if (FREE == Interlocked.CompareExchange(ref slotFlag, FILLING, FREE))
{
fillslot();
old = Interlocked.Exchange(ref slotFlag, READY);
Debug.Assert (FILLING == old);
}
Consumer:
if (READY == Interlocked.CompareExchange(ref slotFlag, DRAINIG, READY))
{
drain_slot();
old = Interlocked.Exchange(ref slotFlag, FREE);
Debug.Assert( DRAINIG == old);
}
This is lock free and quite efficient if you have many cores, many producers and/or many consumers. The problem with this, that is also the problem with using bool, is that there are no wait semantics. Both the Producer and the Consumer will have to spin looking for FREE and respectively READY slots. You can overcome this by adding 'ready' and 'free' events. Also you need to take care of ensuring the ring buffer write/read positions are properly maintained.

Custom Performance Counter / Minute in .NET

I'm trying to create a custom performance counter in C# based on per minute.
So far, I've seen only RateOfCountsPerSecond32 or RateOfCountsPerSecond64 available.
Does anybody know what are options for creating a custom counter based on per minute?
This won't be directly supported. You'll have to computer the rate per minute yourself, and then use a NumberOfItems32 or NumberOfItems64 counter to display the rate. Using a helpful name like "Count / minute" will make it clear what the value is. You'll just update the counter every minute. A background (worker) thread would be a good place to do that.
Alternately, you can just depend upon the monitoring software. Use a NumberOfItems32/64 counter, but have the monitoring software do the per-minute computation. The PerfMon tool built into Windows doesn't do this, but there's no reason it couldn't.
By default PerfMon pulls data every second. In order to get permanent image in Windows performance monitor chart, I've wrote custom counter for measure rate of count per minute.
After working for one minute I become receive data from my counter.
Note that accuracy doesn't important for me.
Code snippet look like this:
class PerMinExample
{
private static PerformanceCounter _pcPerSec;
private static PerformanceCounter _pcPerMin;
private static Timer _timer = new Timer(CallBack, null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
private static Queue<CounterSample> _queue = new Queue<CounterSample>();
static PerMinExample()
{
// RateOfCountsPerSecond32
_pcPerSec = new PerformanceCounter("Category", "ORDERS PER SECOND", false);
// NumberOfItems32
_pcPerMin = new PerformanceCounter("Category", "ORDERS PER MINUTE", false);
_pcPerSec.RawValue = 0;
_pcPerMin.RawValue = 0;
}
public void CountSomething()
{
_pcPerSec.Increment();
}
private static void CallBack(Object o)
{
CounterSample sample = _pcPerSec.NextSample();
_queue.Enqueue(sample);
if (_queue.Count <= 60)
return;
CounterSample prev = _queue.Dequeue();
Single numerator = (Single)sample.RawValue - (Single)prev.RawValue;
Single denomenator =
(Single)(sample.TimeStamp - prev.TimeStamp)
/ (Single)(sample.SystemFrequency) / 60;
Single counterValue = numerator / denomenator;
_pcPerMin.RawValue = (Int32)Math.Ceiling(counterValue);
Console.WriteLine("ORDERS PER SEC: {0}", _pcPerSec.NextValue());
Console.WriteLine("ORDERS PER MINUTE: {0}", _pcPerMin.NextValue());
}
}