Please i need your help and support on how to resolve this problem.My UI thread stopped responding after two updates.In an attempt to solve this problem,i had tried to use Backgroundorker and Asynchronouse programming.With the backgroundwork,my GUI did not respond.Values sent to the GUI did not even show at all,so there was nothing like
updates when i used backgroundworker.However when i used Asynchronouse programming,the value sent to the GUI was displayed and it was updated twice(for example,if the value sent to the GUI is 10,this value(10)will be displayed and then updated to 12).The values sent to the GUI comes from the return value of the function below.
Expand|Select|Wrap|Line Numbers
- ftStatus = myFtdiDevice.Read(readData, numBytesToRead, ref numBytesRead);
- value = Convert.ToString(readData[0]);
- return value;
Below are my program codes for the Backgroundworker and Asynchronouse respectively.
BACKGROUNDWORKER CODE
Expand|Select|Wrap|Line Numbers
- private void checkBox1_CheckedChanged(object sender, EventArgs e)
- {
- if (this.checkBox1.Checked && !this.backgroundWorker1.IsBusy)
- {
- this.backgroundWorker1.RunWorkerAsync();
- }
- else if (!this.checkBox1.Checked && this.backgroundWorker1.IsBusy)
- {
- this.backgroundWorker1.CancelAsync();
- }
- }
- private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
- {
- UInt32 numBytesRead = 0;
- UInt32 numBytesToRead = 1;
- byte[] readData = new byte[10];
- while (!this.backgroundWorker1.CancellationPending)
- {
- // Do some work.
- Thread.Sleep(1000);
- ftStatus = myFtdiDevice.Read(readData, numBytesToRead, ref numBytesRead);
- // Update the UI.
- this.backgroundWorker1.ReportProgress(0, readData[0].ToString());
- }
- }
- private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
- {
- label11.Text = (string)e.UserState + "ºC";
- }
Expand|Select|Wrap|Line Numbers
- private void rxtemp_CheckedChanged(object sender, EventArgs e)
- {
- aTimer = new System.Timers.Timer(1000);
- aTimer.Elapsed += new ElapsedEventHandler(DisplayTempValue);
- aTimer.AutoReset = true;
- aTimer.Enabled = true;
- }
- private string HeavyOperation()
- {
- UInt32 numBytesRead = 0;
- UInt32 numBytesToRead = 1;
- byte[] readData = new byte[255];
- string value;
- ftStatus = myFtdiDevice.Read(readData, numBytesToRead, ref numBytesRead);
- value = Convert.ToString(readData[0]);
- return value;
- }
- private Task<string> HeavyOperationAsync()
- {
- return Task.Run<string>(() => HeavyOperation());
- }
- private async void DisplayTempValue(object source, ElapsedEventArgs e)
- {
- string result = await HeavyOperationAsync();
- label3.Invoke(new Action(() =>
- {
- label3.Text = result + "ºC";
- }));
- }
Best regards.