I a have microchip mcp2200 device. To device is attached tree buttons (as digital inputs).
I use it as feedback machine.
I attached it to windows server 2003 x64. Then i used microchips mcp2200 driver and Managed SimpleIO DLL in my C# app.
In C# i use time with frequency 500 ms to check if button was pressed. After hour or two server has constant high cpu usage. If i kill C# program, all is ok. How can i lover cpu usage? Or my code has wrong?
Some code:
void timer1_Tick(object sender, EventArgs e)
{
if (DateTime.Now.ToString("HH") == _turnOffApp) Environment.Exit(0); //after working hours, turn off app. Task scheduler will start it at 8 AM
if (btn_down == 99)
{ //if button is UP
bool connStatus = SimpleIOClass.IsConnected();
if (connStatus)
{
lblConnStatus.Text = "Connected";
unsafe
{
uint rez1 = 2;
uint* rez = &rez1;
for (uint i = 0; i < 8; i++)
{
if (i == 5 || i == 7) continue; //unused pins
rez1 = 2;
if (SimpleIOClass.ReadPin(i, rez))
{
string rez11 = rez1.ToString();
this.Controls["label" + i.ToString()].Text = rez1.ToString();
if (rez1.ToString() == "0") // 0 = button down, 1 = button up
{
RegisterButton(i);
i = 8;
continue;
}
}
else
{
try { this.Controls["label" + i.ToString()].Text = "ReadPinErr"; }
catch { }
}
}
}
}
else
{
lblConnStatus.Text = "NOT Connected";
}
}//end btn_down == 99
}
void RegisterButton(uint poga)
{
btn_down = poga;
device = Device(poga);
CheckUserInput();
}
void SendBtnToServer(string btn)
{
try
{
string uri = #"http://web-server.lan/pogas.php?device="+ device+ "&p=" + btn;
WebClient clietn = new WebClient();
clietn.Headers.Add("Cache-Control", "no-cache");
clietn.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
clietn.DownloadString(uri);
clietn.Dispose();
}
catch (Exception ex) { try { File.AppendAllText(logFails, DateTime.Now.ToString() + " " + ex.ToString() + "\n\r"); } catch { } }
}
void CheckUserInput()
{
Thread.Sleep(2000); //wait 2 sec until user releases button
bool connStatus = SimpleIOClass.IsConnected();
if (connStatus)
{
lblConnStatus.Text = "Connected";
unsafe
{
uint rez1 = 2;
uint* rez = &rez1;
string ctrName = "label" + btn_down.ToString();
if (SimpleIOClass.ReadPin(btn_down, rez))
{
if (rez1.ToString() == "1") // poga atlaista
{
// register button press
if (btn_down == Pogas["smaids"]) { OSD(":)"); new Thread(() => SendBtnToServer("1")).Start(); }
if (btn_down == Pogas["neitrals"]) { OSD(":|"); new Thread(() => SendBtnToServer("2")).Start(); }
if (btn_down == Pogas["bedigs"]) { OSD(":("); new Thread(() => SendBtnToServer("3")).Start(); }
if (btn_down == Pogas["smaids2"]) { OSD(":)"); new Thread(() => SendBtnToServer("1")).Start(); }
if (btn_down == Pogas["neitrals2"]) { OSD(":|"); new Thread(() => SendBtnToServer("2")).Start(); }
if (btn_down == Pogas["bedigs2"]) { OSD(":("); new Thread(() => SendBtnToServer("3")).Start(); }
}
}
else this.Controls[ctrName].Invoke(new Action(() => this.Controls[ctrName].Text = "Read pin ERROR (Release)"));
}
}
else
{
lblConnStatus.Text = "NOT Connected";
}
btn_down = 99;
}// CheckUserInput
Answer is: C# app is restarted every hour via Scheduled job. No more high cpu usage.
Related
I have the following problem and hope someone can help me.
My basic flow: I want to program any number of devices in parallel using the FTDI D2XX driver and then communicate with them for testing purposes. For this I use two arrays from BackgroundWorker - the first array for programming and the second for testing.
Programming works without any problems. But if I start the BackgroundWorker from the second array to start the test, the connection fails. If I run the complete sequence with only one BackgroundWorker for programming and one BackgroundWorker for testing, the sequence works without problems.
Initialization of BackgroundWorker
private void InitializeBackgoundWorkers()
{
for (var f = 0; f < ftdiDeviceCount; f++)
{
threadArrayProgram[f] = new BackgroundWorker();
threadArrayProgram[f].DoWork += new DoWorkEventHandler(bgr_WorkerStirrerProg_DoWork);
threadArrayProgram[f].RunWorkerCompleted += new RunWorkerCompletedEventHandler(BackgroundWorkerProgRunWorkerCompleted);
threadArrayProgram[f].WorkerReportsProgress = true;
threadArrayProgram[f].WorkerSupportsCancellation = true;
}
for (var f = 0; f < ftdiDeviceCount; f++)
{
threadArrayTest[f] = new BackgroundWorker();
threadArrayTest[f].DoWork += new DoWorkEventHandler(bgr_WorkerStirrerTest_DoWork);
threadArrayTest[f].RunWorkerCompleted += new RunWorkerCompletedEventHandler(BackgroundWorkerTestRunWorkerCompleted);
threadArrayTest[f].WorkerReportsProgress = true;
threadArrayTest[f].WorkerSupportsCancellation = true;
}
}
Aufruf der BackgroundWorker
private void button2_Click_1(object sender, EventArgs e)
{
if (!bStirrerSerached)
{
vSetProgressBarValueRuehrer(1, imaxprogressbar);
vSearchStirrer();
}
if (FtStatus == FTDI.FT_STATUS.FT_OK)
{
//bgr_Worker_Stirrer.RunWorkerAsync();
InitializeBackgoundWorkers();
//---programmieren---//
for (var f = 0; f < /*FilesToProcess*/ftdiDeviceCount; f++)
{
var fileProcessed = false;
while (!fileProcessed)
{
for (var threadNum = 0; threadNum < MaxThreads; threadNum++)
{
if (!threadArrayProgram[threadNum].IsBusy)
{
Console.WriteLine("Starting Thread: {0}", threadNum);
stemp = "Starting Thread: " + threadNum;
File.AppendAllText(slogfile, stemp);
threadArrayProgram[threadNum].RunWorkerAsync(f);
fileProcessed = true;
Thread.Sleep(1000);
break;
}
}
if (!fileProcessed)
{
Thread.Sleep(50);
}
}
}
//---testen---//
for (var f = 0; f < /*FilesToProcess*/ftdiDeviceCount; f++)
{
var fileProcessed = false;
while (!fileProcessed)
{
for (var threadNum = 0; threadNum < MaxThreads; threadNum++)
{
if (!threadArrayTest[threadNum].IsBusy)
{
Console.WriteLine("Starting Thread: {0}", threadNum);
stemp = "Starting Thread: " + threadNum;
File.AppendAllText(slogfile, stemp);
threadArrayTest[threadNum].RunWorkerAsync(f);
fileProcessed = true;
Thread.Sleep(1000);
break;
}
}
if (!fileProcessed)
{
Thread.Sleep(50);
}
}
}
}
button2.Enabled = false;
}
BackgroundWorker
private void bgr_WorkerStirrerProg_DoWork(object sender, DoWorkEventArgs e)
{
try
{
if (FtStatus == FTDI.FT_STATUS.FT_OK)
{
if (ftdiDeviceList != null)
{
//---db werte sammeln---//
cRuehrerProp = new CRuehrerProperties();
cRuehrerProp.SBenutzer = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
cRuehrerProp.SComputername = System.Windows.Forms.SystemInformation.ComputerName.ToString();
//---Rührer programmieren---//
vStirrerProgram((int)e.Argument);
}
}
}
catch (NotSupportedException /*exc*/)
{
}
finally
{
this.Invoke((MethodInvoker)delegate
{
});
}
}
private void bgr_WorkerStirrerTest_DoWork(object sender, DoWorkEventArgs e)
{
try
{
if (!bfinish)
{
while (!bfinish)
{
if (bfinish)
break;
}
}
//---Test starten---//
vStirrerTest((int)e.Argument);
}
catch (NotSupportedException /*exc*/)
{
}
finally
{
this.Invoke((MethodInvoker)delegate
{
button2.Enabled = true;
myFtdiDevice.Close();
});
}
}
Testing method
private void vStirrerTest(int pos)
{
//threadnr
iPosRuehrerGrid = pos;
Console.WriteLine("Thread {0} StirrerTest", pos);
ftStatus = myFtdiDevice.CyclePort();
UInt32 newFtdiDeviceCount = 0;
do
{
// Wait for device to be re-enumerated
// The device will have the same location since it has not been
// physically unplugged, so we will keep trying to open it until it succeeds
ftStatus = myFtdiDevice.OpenByLocation(ftdiDeviceList[iPosRuehrerGrid].LocId);
Console.WriteLine("try to open locid" + ftdiDeviceList[iPosRuehrerGrid].LocId + " on device " + iPosRuehrerGrid);
//ftStatus = myFtdiDevice.OpenByLocation(ftdiDeviceListOrig[iStirrerPosold[iPosRuehrerGrid]].LocId);
Thread.Sleep(1000);
} while (ftStatus != FTDI.FT_STATUS.FT_OK);
// Close the device
myFtdiDevice.Close();
// Re-create our device list
ftStatus = myFtdiDevice.GetNumberOfDevices(ref newFtdiDeviceCount);
if (ftStatus != FTDI.FT_STATUS.FT_OK)
{
// Wait for a key press
Console.WriteLine("Failed to get number of devices (error " + ftStatus.ToString() + ")");
stemp = "Failed to get number of devices (error " + ftStatus.ToString() + ")";
File.AppendAllText(slogfile, stemp);
return;
}
// Re-populate our device list
ftStatus = myFtdiDevice.GetDeviceList(ftdiDeviceList);
bRepopulateList = true;
vSearchStirrer();
The error occurs in the do loop. If I use only one device - and thus only one thread at a time, it takes an average of 5 runs until the device is opened again. However, if I attach another device and thus have 2 programming and 2 test threads, it does not manage to open the desired device.
I have looked at the DeviceList to make sure it is looking for the right device with the right ID - which it is.
Since I don't have any experience with the Backgrounworker yet, I'm not sure if I haven't forgotten something, which is why this error occurs.
So I have this function, designed to download YouTube videos from the internet.
However whenever I run it, it does not catch any exception. Even an explicitly thrown new exception().
It's a WPF program so before anyone mentions bad coding etiquette, please don't. I'm more concerned with getting my program working at the moment.
Here's the code that creates the thread:
void button1_Click (object sender, RoutedEventArgs e)
{
this.IsEnabled = false;
this.downloadProgressText.Text = "Beginning....";
int selectedIndex = this.queueListView.SelectedIndex;
Thread newThread = new Thread (() => Download_Handler(classContainer, 0, selectedIndex, 0));
newThread.Start();
}
And the threaded function itself:
private void Download_Handler (ClassContainer classCont, int curVidPosition, int selectedIndex, int retryCount)
{
ObservableCollection<Video> finishedUrls = new ObservableCollection<Video> ();
ObservableCollection<Video> urlList = videoQueue.Items;
for (int position = curVidPosition, urlListCount = urlList.Count; position < urlListCount; position++)
{
try
{
downloadProgressText.Dispatcher.Invoke(new UpdateSelectedListItemCallback (this.UpdateSelectedListItem), new object[] {
position
});
Video vid = urlList [position];
if (classCont.DownloadingCode.DownloadVideo(vid, this, position) != null)
{
finishedUrls.Add(vid);
}
if (finishedUrls != null && finishedUrls.Count > 0)
{
classCont.IOHandlingCode.WriteUrlsToFile(finishedUrls, true);
}
}
catch (Exception ex)
{
var exceptionMessage = ex.Message;
if (retryCount <= 4)
{
downloadProgressText.Dispatcher.Invoke(new UpdateProgressBarCallback (this.UpdateProgressBar), new object[] {
string.Format(CultureInfo.InstalledUICulture, "URL {0}: {1}. Retrying.... ({2}/{3})", position + 1, classContainer.ConversionCode.Truncate(exceptionMessage, 50), retryCount.ToString(CultureInfo.CurrentCulture), "3"),
-1
});
Thread.Sleep(850);
Download_Handler(classCont, position, selectedIndex, retryCount + 1);
}
else
{
if (finishedUrls.Count < 10)
{
finishedUrls.Clear();
}
downloadProgressText.Dispatcher.Invoke(new UpdateProgressBarCallback (this.UpdateProgressBar), new object[] {
classCont.ConversionCode.Truncate(exceptionMessage, 100),
-1
});
}
}
}
videoQueue.Items = finishedUrls.Count > 0 ? (ObservableCollection<Video>)urlList.Where(video => finishedUrls.All(item => item != video)).Select(video => video) : urlList;
if (this.queueListView.Items.Count > 0)
{
this.RefreshQueue(videoQueue.Items, selectedIndex < this.queueListView.Items.Count ? 0 : selectedIndex);
}
this.IsEnabled = true;
}
This coding scheme worked just fine in WinForms (well, with slight differences), but since the move to WPF I just cannot figure it out!
EDIT:
Including additional code:
public Video DownloadVideo (Video video, MainWindow MainForm, int position)
{
MainForm.Dispatcher.Invoke(new MainWindow.UpdateProgressBarCallback (MainForm.UpdateProgressBar), new object[] {
0,
string.Format(CultureInfo.InstalledUICulture, "Beginning download from '{0}'", video.Location)
});
/*
* Get the available video formats.
* We'll work with them in the video and audio download examples.
*/
IEnumerable<VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(video.Location, false);
if ((video.Format != VideoType.Mp4 && videoInfos.Any(info => (info.Resolution == video.Resolution && info.VideoType == video.Format)) || video.Format == VideoType.Mp4 && video.Resolution == 360))
{
VideoInfo currentVideo = videoInfos.First(info => info.VideoType == video.Format && info.Resolution == video.Resolution);
MainForm.Dispatcher.Invoke(new MainWindow.UpdateProgressBarCallback (MainForm.UpdateProgressBar), new object[] {
-1,
string.Format(CultureInfo.InstalledUICulture, "Downloading '{0}{1}' at {2}p resolution", Conversion.Truncate(currentVideo.Title, 56), currentVideo.VideoExtension, currentVideo.Resolution)
});
//DownloadAudio(videoInfos);
this.Download_Actual(videoInfos, MainForm, video.Resolution, position, video.Format);
return video;
}
if (videoInfos.Where(info => info.VideoType == video.Format).All(info => info.Resolution != video.Resolution) || (video.Format == VideoType.Mp4 && video.Resolution != 360))
{
List<int> resolutionsEstablished = new List<int> ();
List<VideoType> formatsEstablished = new List<VideoType> ();
using (StreamWriter outfile = new StreamWriter ("Acceptable Options.txt"))
{
outfile.Write(string.Format(CultureInfo.InstalledUICulture, "This file will show you all formats available for the current URL, as well as the resolutions that are acceptable for that URL.\n\n{0}:\n", video.Location));
foreach (VideoType format in videoInfos.Where(info => info.VideoType != VideoType.Unknown && formatsEstablished.All(format => info.VideoType != format)).Select(info => info.VideoType))
{
if (format == VideoType.Mp4)
{
outfile.Write(string.Format(CultureInfo.InstalledUICulture, "Format: {0} | Resolution: {1}p\n", format, "360"));
}
else
{
foreach (int resolution in videoInfos.Where(info => info.Resolution >= 144 && info.Resolution < 720 && resolutionsEstablished.All(res => info.Resolution != res) && info.VideoType == format).Select(info => info.Resolution))
{
outfile.Write(string.Format(CultureInfo.InstalledUICulture, "Format: {0} | Resolution: {1}p\n", format, resolution));
resolutionsEstablished.Add(resolution);
}
}
resolutionsEstablished.Clear();
formatsEstablished.Add(format);
}
}
throw new NotSupportedException("An acceptable options file has been exported to the program's root folder. Check there for more information.");
}
return null;
}
private void Download_Actual (IEnumerable<VideoInfo> videoInfos, MainWindow MainForm, int resolution, int position, VideoType format)
{
/*
* Select the first .mp4 video with 360p resolution
*/
VideoInfo video = videoInfos
.First(info => info.VideoType == format && info.Resolution == resolution);
/*
* If the video has a decrypted signature, decipher it
*/
if (video.RequiresDecryption)
{
DownloadUrlResolver.DecryptDownloadUrl(video);
}
/*
* Create the video downloader.
* The first argument is the video to download.
* The second argument is the path to save the video file.
*/
Settings settings = Storage.ReadFromRegistry();
var videoName = RemoveIllegalPathCharacters(video.Title) + video.VideoExtension;
var videoPath = Path.Combine(settings.TemporarySaveLocation, videoName);
var finalPath = Path.Combine(settings.MainSaveLocation, videoName);
if (!File.Exists(finalPath))
{
var videoDownloader = new VideoDownloader (video, videoPath);
// Register the ProgressChanged event and print the current progress
videoDownloader.DownloadProgressChanged += (
(sender, args) => MainForm.downloadProgressBar.Dispatcher.Invoke(new MainWindow.UpdateProgressBarCallback (MainForm.UpdateProgressBar), new object[] {
(int)args.ProgressPercentage,
null
})
);
/*
* Execute the video downloader.
* For GUI applications note, that this method runs synchronously.
*/
videoDownloader.Execute();
File.Move(videoPath, finalPath);
}
else
{
MainForm.downloadProgressText.Dispatcher.Invoke(new MainWindow.UpdateProgressBarCallback (MainForm.UpdateProgressBar), new object[] {
0,
null
});
throw new FieldAccessException("{0}({1}) already exists! Download process has been aborted and considered successful.");
}
}
I've stripped your code back to basics and works fine for me. Would probably need a complete code sample
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
Thread newThread = new Thread(Download_Handler);
newThread.Start();
}
private void Download_Handler()
{
try
{
throw new Exception();
}
catch (Exception)
{
}
}
I figured it out. It was really stupid of a mistake....
So I call public delegate void UpdateProgressBarCallback (int progress, string message); to update text and progress bar values.
In this case, in the catch block, I was attempting to pass as the other way around, IE public delegate void UpdateProgressBarCallback (string message, int progress);. THAT'S why it was being weird. It all works now.
Hi guys I have such construction:
Start threads:
Thread[] thr;
int good_auth, bad_auth, good_like, bad_like;
static object accslocker = new object();
static object limitlocker = new object();
string acc_path, proxy_path, posts_path;
int position_of_limit, position = 0;
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
button2.Enabled = true;
decimal value = numericUpDown1.Value;
int i = 0;
int j = (int)(value);
thr = new Thread[j];
for (; i < j; i++)
{
thr[i] = new Thread(new ThreadStart(go));
thr[i].IsBackground = true;
thr[i].Start();
}
}
And than function go:
public void go()
{
while (true)
{
string acc = "";
string proxy = "";
lock (limitlocker)
{
if (position_of_limit >= int.Parse(textBox2.Text) - 1)
{
position_of_limit = 0;
if (position < posts.Count - 1)
position++;
else
{
break;
}
}
}
lock (accslocker)
{
if (accs.Count == 0)
{
break;
}
else
acc = accs.Dequeue();
}
OD od = new OD(acc);
string login = od.Auth();
if (login == "Login")
{
lock (accslocker)
{
good_auth++;
log_good_auth(good_auth);
}
string like = od.like(posts[position], textBox1.Text);
if (like == "Good")
{
lock (accslocker)
{
position_of_limit++;
good_like++;
log_good_like(good_like);
}
}
else if (like == "Failed")
{
lock (accslocker)
{
bad_like++;
log_bad_like(bad_like);
}
}
else
{
lock (accslocker)
{
bad_like++;
log_bad_like(bad_like);
}
}
}
else if (login == "Spamblock")
{
lock (accslocker)
{
bad_auth++;
log_bad_auth(bad_auth);
}
}
else if (login == "Locked")
{
lock (accslocker)
{
bad_auth++;
log_bad_auth(bad_auth);
}
}
else if (login == "Invalid")
{
lock (accslocker)
{
bad_auth++;
log_bad_auth(bad_auth);
}
}
else if (login == "Bad_proxy")
{
lock (accslocker)
{
accs.Enqueue(acc);
Proxy.proxies.Remove(proxy);
}
}
else
{
lock (accslocker)
{
accs.Enqueue(acc);
Proxy.proxies.Remove(proxy);
}
}
}
}
I start for example 20 threads, when position_of_limit becomes bigger than int.Parse(textBox2.Text) - 1 all threads need to take next posts[position] in next loop. But I receive an exception on line string like = od.like(posts[position], textBox1.Text);
"Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index"
How to solve this problem? Thanks
Locking the GUI thread is evil, since it's an STA thread.
That means it must manage a message loop and is not allowed to block. So blocking is likely to cause deadlocks.
Rather use callbacks like BackgroundWorker.RunWorkerCompleted.
Some other informative links about locking:
Guidelines of when to use locking
Obtaining lock on a UI thread
I read somewhere that i need to dispose objects when closing the application ?
I have this properties i did to use them in tow functions i needed to invoke them since im using a backgroundworker.
In most of the times when i closed my application it was ok but now i got this exception.
private string CpuTextLabelProperty
{
set
{
if (InvokeRequired)
{
BeginInvoke(new Action(() => CpuTemperature_label.Text = value), null);
}
}
get
{
return CpuTemperature_label.Text;
}
}
private Point CpuLocationLabelProperty
{
set
{
if (InvokeRequired)
{
BeginInvoke(new Action(() => CpuTemperature_label.Location = new Point(210, 200)), null);
}
}
get
{
return CpuTemperature_label.Location;
}
}
private string GpuTextLabelProperty
{
set
{
if (InvokeRequired)
{
BeginInvoke(new Action(() => GpuTemperature_label.Text = value), null);
}
}
get
{
return GpuTemperature_label.Text;
}
}
private Point GpuLocationLabelProperty
{
set
{
if (InvokeRequired)
{
BeginInvoke(new Action(() => GpuTemperature_label.Location= new Point(210,100)), null);
}
}
get
{
return GpuTemperature_label.Location;
}
}
private string Label4TextProperty
{
set
{
if (InvokeRequired)
{
BeginInvoke(new Action(() => label4.Text = value), null);
}
}
}
The exception is on the property: GpuTextLabelProperty inside the get on the line:
return GpuTemperature_label.Text;
Win32Exception - Error creating window handle
My Form1 closing event:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (MessageBox.Show("Are you Sure you want to Exit. Click Yes to Confirm and No to continue", "WinForm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
e.Cancel = true;
}
else
{
this.BeginInvoke((MethodInvoker)delegate { this.Close(); });
}
}
If i need ot dispose something wich ones ? And how ?
This is the functions im using the properties:
private void cpuView()
{
Computer myComputer = new Computer();
myComputer = new Computer(settings) { CPUEnabled = true };
myComputer.Open();
Trace.WriteLine("");
foreach (var hardwareItem in myComputer.Hardware)
{
if (hardwareItem.HardwareType == HardwareType.CPU)
{
hardwareItem.Update();
foreach (IHardware subHardware in hardwareItem.SubHardware)
subHardware.Update();
foreach (var sensor in hardwareItem.Sensors)
{
settings.SetValue("sensor", sensor.Value.ToString());
if (sensor.SensorType == SensorType.Temperature)
{
sensor.Hardware.Update();
settings.GetValue("sensor", sensor.Value.ToString());
int t = CpuTextLabelProperty.Length;
if (t >= 4)
{
CpuLocationLabelProperty = new Point(210, 200); // not working to check everything about the locations \\
}
else
{
CpuLocationLabelProperty = new Point(250, 200);
}
CpuTextLabelProperty = sensor.Value.ToString() + "c";//String.Format("{0} Temperature = {1}c", sensor.Name, sensor.Value.HasValue ? sensor.Value.Value.ToString() : "no value");
tempCpuValue = sensor.Value;
break;
}
}
}
}
}
private void gpuView()
{
Computer computer = new Computer();
computer.Open();
computer.GPUEnabled = true;
foreach (var hardwareItem in computer.Hardware)
{
if (videoCardType("ati", "nvidia") == true)
{
HardwareType htype = HardwareType.GpuNvidia;
if (hardwareItem.HardwareType == htype)
{
foreach (var sensor in hardwareItem.Sensors)
{
if (sensor.SensorType == SensorType.Temperature)
{
sensor.Hardware.Update();
if (sensor.Value.ToString().Length > 0)
{
if (GpuTextLabelProperty.Length < 1)
{
if (UpdatingLabel(sensor.Value.ToString(), string.Empty))
{
// Label8 = GpuText;
}
}
else if (UpdatingLabel(sensor.Value.ToString(), GpuTextLabelProperty.Substring(0, GpuTextLabelProperty.Length - 1)))
{
// Label8 = GpuText;
}
GpuTextLabelProperty = sensor.Value.ToString() + "c";
tempGpuValue = sensor.Value;
//label8.Visible = true;
}
int t = GpuTextLabelProperty.Length;
if (t >= 4)
{
GpuLocationLabelProperty = new Point(210, 100);
}
else
{
GpuLocationLabelProperty = new Point(250, 100);
}
// timer2.Interval = 1000;
if (sensor.Value > 90)
{
Logger.Write("The current temperature is ===> " + sensor.Value);
button1.Enabled = true;
}
//this.Select();
}
}
}
}
else
{
HardwareType htype = HardwareType.GpuAti;
if (hardwareItem.HardwareType == htype)
{
foreach (var sensor in hardwareItem.Sensors)
{
if (sensor.SensorType == SensorType.Temperature)
{
sensor.Hardware.Update();
if (sensor.Value.ToString().Length > 0)
{
if (GpuTextLabelProperty.Length < 1)
{
if (UpdatingLabel(sensor.Value.ToString(), string.Empty))
{
// Label8 = GpuText;
}
}
else if (UpdatingLabel(sensor.Value.ToString(), GpuTextLabelProperty.Substring(0, GpuTextLabelProperty.Length - 1)))
{
// Label8 = GpuText;
}
GpuTextLabelProperty = sensor.Value.ToString() + "c";
tempGpuValue = sensor.Value;
//label8.Visible = true;
}
int t = GpuTextLabelProperty.Length;
if (t >= 4)
{
GpuLocationLabelProperty = new Point(210, 100);
}
else
{
GpuLocationLabelProperty = new Point(250, 100);
}
//timer2.Interval = 1000;
if (sensor.Value > 90)
{
Logger.Write("The current temperature is ===> " + sensor.Value);
button1.Enabled = true;
}
this.Select();
}
}
}
}
}
}
And this is the full exception message:
System.ComponentModel.Win32Exception was unhandled by user code
Message=Error creating window handle.
Source=System.Windows.Forms
ErrorCode=-2147467259
NativeErrorCode=87
StackTrace:
at System.Windows.Forms.NativeWindow.CreateHandle(CreateParams cp)
at System.Windows.Forms.Control.CreateHandle()
at System.Windows.Forms.Control.get_Handle()
at System.Windows.Forms.Control.get_WindowText()
at System.Windows.Forms.Control.get_Text()
at System.Windows.Forms.Label.get_Text()
at HardwareMonitoring.Form1.get_GpuTextLabelProperty() in D:\C-Sharp\HardwareMonitoring\HardwareMonitoring\Hardwaremonitoring\Form1.cs:line 613
at HardwareMonitoring.Form1.gpuView() in D:\C-Sharp\HardwareMonitoring\HardwareMonitoring\Hardwaremonitoring\Form1.cs:line 412
at HardwareMonitoring.Form1.backgroundWorker1_DoWork(Object sender, DoWorkEventArgs e) in D:\C-Sharp\HardwareMonitoring\HardwareMonitoring\Hardwaremonitoring\Form1.cs:line 670
at System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e)
at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument)
InnerException:
You have to stop your background worker when you close or exit your application. The exceptions gets thrown at you because the objects your code is relying on are being torn down by the OS.
See this thread on how to do it.
I am trying to code a multithreaded WebBrowser application.
The WebBrowser elements will just navigate to a given URL,
wait until it loads and then
click a button or
submit the form.
This should happen in a loop forever.
I'm using Microsoft Visual Studio 2010 and Windows Forms
Here's my code:
//added windows form 30 webbrowser object
//and now assigning them to an webbrowser array
wbList[0] = webBrowser1; wbList[1] = webBrowser2; wbList[2] = webBrowser3;
wbList[3] = webBrowser4; wbList[4] = webBrowser5; wbList[5] = webBrowser6;
wbList[6] = webBrowser7; wbList[7] = webBrowser8; wbList[8] = webBrowser9;
//etc. until:
wbList[29] = webBrowser30;
for (int i = 0; i < 30; i++)
{
wbList[i].ScriptErrorsSuppressed = true;
wbList[i].NewWindow += new CancelEventHandler(wb_NewWindow);
}
//********************************** creating threads here
Thread[] AllThread = new Thread[100];
int irWhichWbb = 0;
for (int nn = irDirectPostCount; nn < irNumber+1; nn++)
{
AllThread[nn] = new Thread(new
ParameterizedThreadStart(this.MultiThreadWebBrowser));
AllThread[nn].Start(nn.ToString() + ";" + irWhichWbb.ToString());
irWhichWbb++;
}
Application.DoEvents();
for (int nn = 0; nn < irNumber+1; nn++)
{ AllThread[nn].Join(); }
//Multi thread function
void MultiThreadWebBrowser(object parameter)
{
string srParam = parameter.ToString();
int i = Convert.ToInt32 (srParam.Substring(0,(srParam.IndexOf(";"))));
int irWhichWb = Convert.ToInt32(srParam.Substring(srParam.IndexOf(";")+1));
string hdrs = "Referer: http://www.xxxxxxxxx.com/xxxxxxxxxx.aspx";
try
{
wbList[irWhichWb].Navigate(srVotingList[i, 0], "_self", null, hdrs);
}
catch { }
try { waitTillLoad(irWhichWb); }
catch { }
waitTillLoad3();
}
// wait until webbrowser navigate url loaded
private void waitTillLoad(int irWhichLoad)
{
WebBrowserReadyState loadStatus;
//wait till beginning of loading next page
int waittime = 100000;
int counter = 0;
while (true)
{
try
{
loadStatus = wbList[irWhichLoad].ReadyState;
Application.DoEvents();
if ((counter > waittime) ||
(loadStatus == WebBrowserReadyState.Uninitialized) ||
(loadStatus == WebBrowserReadyState.Loading) ||
(loadStatus == WebBrowserReadyState.Interactive))
{
break;
}
counter++;
}
catch { }
}
//wait till the page get loaded.
counter = 0;
while (true)
{
try
{
loadStatus = wbList[irWhichLoad].ReadyState;
Application.DoEvents();
if (loadStatus == WebBrowserReadyState.Complete)
{
break;
}
if (counter > 10000000)
break;
counter++;
}
catch { }
}
}
private void waitTillLoad3()
{
DateTime dtStart = DateTime.Now;
while (true)
{
if ((DateTime.Now - dtStart).TotalMilliseconds > 4000)
break;
Application.DoEvents();
}
}
You don't say what kind of failure you get: "doesn't work" is not a good description.
I would first try with just a single thread. Does that work?
You have empty catch blocks, so you are silently ignoring some error conditions. This may well by hiding a problem.