TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Alex Dunlop
NA
13
893
How to modify UI from an another thread?
Feb 11 2021 7:39 PM
Hi friends,
For testing and learning purposes, I tried to write a code which simulates some calculations. I used BackGroundWorker to avoid GUI freeze during calculation. My problem is that I want to make change in UI, for example, changing a button's text. I added it to DoWork section of my code. Consider that my operations order needs to be kept. There is runtime error says cross-thread exception. I think I have to use Invoke and Delegate for solving my problem. Please write me a code for solving this problem. I would learn from your code.
Thanks.
private
void
backgroundWorker1_DoWork(
object
sender, DoWorkEventArgs e)
{
button1.Text =
"processing"
;
int
sum = 0;
for
(
int
i = 0; i <= 100; i++)
{
Thread.Sleep(100);
sum = sum + i;
backgroundWorker1.ReportProgress(i);
if
(backgroundWorker1.CancellationPending)
{
e.Cancel =
true
;
backgroundWorker1.ReportProgress(0);
return
;
}
}
e.Result = sum;
}
private
void
backgroundWorker1_ProgressChanged(
object
sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
label1.Text = e.ProgressPercentage +
"%"
;
}
private
void
backgroundWorker1_RunWorkerCompleted(
object
sender, RunWorkerCompletedEventArgs e)
{
if
(e.Cancelled)
{
label1.Text =
"Process canceled"
;
}
else
if
(e.Error !=
null
)
{
label1.Text = e.Error.Message;
}
else
{
label1.Text =
"Result: "
+ e.Result.ToString();
}
}
private
void
button1_Click(
object
sender, EventArgs e)
{
if
(!backgroundWorker1.IsBusy)
{
backgroundWorker1.RunWorkerAsync();
}
else
{
MessageBox.Show(
"Busy processing!. Please wait..."
);
}
}
private
void
button2_Click(
object
sender, EventArgs e)
{
if
(backgroundWorker1.IsBusy)
{
backgroundWorker1.CancelAsync();
}
else
{
label1.Text =
"No operation is running to cancel."
;
}
}
}
Reply
Answers (
2
)
login credentials are not displaying in database
Need help optimizing my code.