I am creating and setting up the performance counters correctly but when I delete the category, recreate the category with the same name and add/update the counters to that category, it fails to update the counters and its values.
The following code runs fine for the first time but not the second time. The code to remove the "Delete category" is not needed right now but I want to be able to delete existing category each time we deploy our application.
How can I permanently delete the counter if its not doing so or reset its values?
private PerformanceCounter mainCounter;
private PerformanceCounter mainCounterBase;
private string category = "TestPerformanceCounterTest";
public void Test()
{
//Counter setup
if (PerformanceCounterCategory.Exists(category))
PerformanceCounterCategory.Delete(category);
if (!PerformanceCounterCategory.Exists(category))
{
var categoryCollection = new CounterCreationDataCollection();
var counter1 = new CounterCreationData("RawCounter1", "", PerformanceCounterType.RawFraction);
var counter2 = new CounterCreationData("RawCounterBase1", "", PerformanceCounterType.RawBase);
categoryCollection.Add(counter1);
categoryCollection.Add(counter2);
PerformanceCounterCategory.Create(category, "", PerformanceCounterCategoryType.SingleInstance, categoryCollection);
// Wait and wait...
Thread.Sleep(TimeSpan.FromSeconds(3));
}
//create counters
mainCounter = new PerformanceCounter(category, "RawCounter1", false);
mainCounterBase = new PerformanceCounter(category, "RawCounterBase1", false);
//reset values
mainCounter.RawValue = 0;
mainCounterBase.RawValue = 0;
//update counter
mainCounter.IncrementBy(10);
mainCounterBase.IncrementBy(20);
**Console.WriteLine("Main counter: " +mainCounter.RawValue);//doesnt show value 50 the second time this is run**
Console.WriteLine("Main counter Base: " + mainCounterBase.RawValue);
Console.WriteLine("Main counter next value: " + mainCounter.NextValue());
Console.WriteLine("Main counter base next value: " + mainCounterBase.NextValue());
}