Reputation: 31
I`m writing a program in c# that tracks CPU usage but i cant get an error solved,
"Cannot implicitly convert Ulong to int".
Code below:
int i;
i = 0;
try
{
ManagementClass cpuDataClass = new ManagementClass("Win32_PerfFormattedData_PerfOS_Processor");
while (true)
{
ManagementObjectCollection cpuDataClassCollection = cpuDataClass.GetInstances();
foreach (ManagementObject obj in cpuDataClassCollection)
{
if (obj["Name"].ToString() == "_Total")
{
i = Convert.ToUInt64(obj["C1TransitionsPersec"]);
}
}
Thread.Sleep(100);
}
}
catch (ThreadAbortException tbe)
{
}
progressBar1.Maximum = 100;
progressBar1.Minimum = 1;
progressBar1.Value = i;
}
I`m fairly new to C# so i hope this is an easy fix,Anyone that can help me in this?
Upvotes: 0
Views: 9696
Reputation: 51
ONLY if you are sure your ulong
variable value will practically stay within the range that int
variable can accommodate, then you can do this:
ulong ulongVar = 100;
int intVar = Convert.ToInt32(ulongVar.ToString());
Upvotes: 2
Reputation: 1
Basicly you only need convert the property C1TransitionsPersec to a Int32 value. I searched about the managed class Win32_PerfFormattedData_PerfOS_Processor that you are using, to view the properties etc, but class I find nearer was Win32_PerfRawData_PerfOS_Processor, AND it was not in Microsoft docs. The property C1TransitionsPersec is a Int64, so if you do a direct cast, your progress bar goes show a far from real values, I strong recommend you do a proportional convertion, get the max value(or get a value that makes sense) and do the math
Upvotes: 0
Reputation: 98750
Error message is self explanatory..
Your i
is int
but Convert.ToUInt64
returns ulong
and there is no implicit conversation between from ulong
to int
because int type doesn't have enough range to keep a ulong
value.
As a quick solution, change your data type to ulong
as;
ulong i;
but you still get a problem on
progressBar1.Value = i;
line since Value
property is int
type. And even if you cast it as (int)i
, you will get different values if your i
is bigger than int.MaxValue
or less than int.MinValue
in checked
mode.
Upvotes: 1