Filling RichTextbox with many lines hangs UI? - c#

I am filling Richtextbox with adding lines from another thread that extract links from web. when the web urls links increase and go more than 9000 it hangs the UI and take long time don't know why ! , using button click event to fire this method ( thread )
Using AppendText(Environment.NewLine) method to fill the richtextbox
Here is the snippet code of my work :
if (URLLMemoRichTxt.Lines.Length == 0)
{
XtraMessageBox.Show("You have to get some links first");
return;
}
var thd = new Thread(() =>
{
if (this.InvokeRequired)
{
if (URLLMemoRichTxt.InvokeRequired)
{
URLLMemoRichTxt.Invoke((MethodInvoker)delegate ()
{
foreach (string line in URLLMemoRichTxt.Lines)
{
if (!GetEmailsListArraylist.Contains(line) && line.Trim() != string.Empty)
{
if (LinksToGetEmailsRichTxt.InvokeRequired)
{
LinksToGetEmailsRichTxt.Invoke((MethodInvoker)delegate ()
{
GetEmailsListArraylist.Add(line);
// LinksToGetEmailsRichTxt.Text += line + "\n";
LinksToGetEmailsRichTxt.AppendText(Environment.NewLine + line);
LinksToGetEmailsLabel.Text = LinksToGetEmailsRichTxt.Lines.Length.ToString();
});
}
else
{
GetEmailsListArraylist.Add(line);
// LinksToGetEmailsRichTxt.Text += line + "\n";
LinksToGetEmailsRichTxt.AppendText(Environment.NewLine + line);
LinksToGetEmailsLabel.Text = LinksToGetEmailsRichTxt.Lines.Length.ToString();
}
}
}
});
}
else
{
foreach (string line in URLLMemoRichTxt.Lines)
{
if (!GetEmailsListArraylist.Contains(line) && line.Trim() != string.Empty)
{
GetEmailsListArraylist.Add(line);
// LinksToGetEmailsRichTxt.Text += line + "\n";
LinksToGetEmailsRichTxt.AppendText(Environment.NewLine + line);
LinksToGetEmailsLabel.Text = LinksToGetEmailsRichTxt.Lines.Length.ToString();
}
}
if (MainTabcontrol.InvokeRequired)
{
MainTabcontrol.Invoke((MethodInvoker)delegate ()
{
MainTabcontrol.SelectedTabPageIndex = 1;
});
}
else
{
MainTabcontrol.SelectedTabPageIndex = 1;
}
}
}
else
{
}
if (MainTabcontrol.InvokeRequired)
{
MainTabcontrol.Invoke((MethodInvoker)delegate ()
{
MainTabcontrol.SelectedTabPageIndex = 1;
});
}
else
{
MainTabcontrol.SelectedTabPageIndex = 1;
}
});
thd.SetApartmentState(ApartmentState.MTA);
thd.Start();

using button click event to fire this method ( thread )
Here is your code, boiled down:
private void button1_Click(object sender, EventArgs e)
{
new Thread(() =>
{
if (URLLMemoRichTxt.InvokeRequired)
{
URLLMemoRichTxt.Invoke((MethodInvoker)delegate ()
{
// .. do some "work" in here ...
Thread.Sleep(9000);
});
}
}).Start();
}
Let's analyze what's happening here:
User clicks the button.
Running in the UI thread, the Click event creates a New Thread and starts it.
Inside that new thread, immediately ask if we are running in a different thread than the one that owns the RichTextBox with InvokeRequired (the answer is, of course, yes!).
Tell the application to run some code on the thread that owns the RichTextBox with Invoke().
Running in the UI thread again, do the actual "work".
End Result?
All your "work" is run in the main UI thread as if no threading ever occurred.
Why create a thread and then tell it to run its work back on the UI thread?
How should it be done correctly?
Here's a slightly more robust version of the boiled down code, with only the part that updates the UI within the Invoke() block:
private void button1_Click(object sender, EventArgs e)
{
new Thread(() =>
{
// do some "work" in our new thread
for(int i = 1; i <= 10; i++)
{
Thread.Sleep(1000); // the "work"
// when you need to UPDATE THE UI, now is the time for Invoke()
// note that only the part that is updating the UI is within this block
// the rest of the code/loop is still running in the new thread
URLLMemoRichTxt.Invoke((MethodInvoker)delegate ()
{
URLLMemoRichTxt.AppendText("Line " + i.ToString() + "\r\n");
});
// ... possibly more work in the new thread ...
}
}).Start();
}
With this approach, the UI will remain responsive while the for loop runs and the work is done. Additionally, the RichTextBox will happily update with the new entries without blocking.

Related

Using timer to refresh interface, keep getting "There is already an open DataReader associated with this Connection which must be closed first."

I've been using a timer to refresh the listview on my application, but after half a second, I get the error message at first try/catch method in RefreshPlot() in PlotComponent.cs:
An exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in Marketplace.exe but was not handled in user code
Additional information: There is already an open DataReader associated
with this Connection which must be closed first.
What is this down to? I'm tried using using and try/catch, so I am not really clear on the mistake I could be making. When I disable the timer everything works well. But I need to access the database every 0.5 seconds in order to refresh the listview.
If I am not doing it the correct way is there anything else I can do?
Code is as follows:
MainWindow.cs
public MainWindow()
{
InitializeComponent();
// Reset lists
SetPlotList(_filterPlotReference);
// Refresh lists
Refresh();
}
public void Refresh()
{
var myTimer = new System.Timers.Timer();
myTimer.Elapsed += RefreshPlotList;
myTimer.Interval = 500;
myTimer.Enabled = true;
}
public void RefreshPlotList(object source, ElapsedEventArgs e)
{
PlotComponent.RefreshPlot();
Dispatcher.Invoke(() =>
{
if (!string.IsNullOrWhiteSpace(FilterTextBox.Text) &&
(!Regex.IsMatch(FilterTextBox.Text, "[^0-9]")))
{
_filterPlotReference = Convert.ToInt32(FilterTextBox.Text);
}
});
SetPlotList(_filterPlotReference);
FocusPlotItem(_focusPlotReference);
}
public void SetPlotList(int filterReference)
{
// Fill plot list view
List<PlotComponent.PlotList> plotList = PlotComponent.SelectPlotLists(filterReference);
// Find the plot list item in the new list
PlotComponent.PlotList selectPlotList =
plotList.Find(x => Convert.ToInt32(x.PlotId) == _focusPlotReference);
Dispatcher.Invoke(
(() =>
{
PlotListView.ItemsSource = plotList;
if (selectPlotList != null)
{
PlotListView.SelectedItem = selectPlotList;
}
}));
int jobSum = 0;
int bidSum = 0;
foreach (PlotComponent.PlotList item in PlotListView.Items)
{
jobSum += Convert.ToInt32(item.Jobs);
bidSum += Convert.ToInt32(item.Bids);
}
// Determine job/bid list ratio
Dispatcher.BeginInvoke(
new ThreadStart(() => JobBidRatioTextBlock.Text = jobSum + " jobs - " + bidSum + " bids"));
}
private void FocusPlotItem(int focusPlotReference)
{
Dispatcher.Invoke(
(() =>
{
PlotComponent.PlotList plotList =
PlotListView.Items.OfType<PlotComponent.PlotList>()
.FirstOrDefault(p => Convert.ToInt32(p.PlotId) == focusPlotReference);
if (plotList == null) return;
//get visual container
var container = PlotListView.ItemContainerGenerator.ContainerFromItem(plotList) as ListViewItem;
if (container == null) return;
container.IsSelected = true;
container.Focus();
}));
}
DbConnect.cs
http://pastebin.com/pZ0PGrg1
PlotComponent.cs
http://pastebin.com/xiRhKyMM
Thanks so much for your help in advance.
Here is an example to lock timer till it finishes its work:
bool timerRunning = false; // define it as a global variable
// then in your timer process add this easy check
public void RefreshPlotList(object source, ElapsedEventArgs e)
{
if(timerRunning) return; // return if it is busy
timerRunning = true; // set it to busy
PlotComponent.RefreshPlot();
Dispatcher.Invoke(() =>
{
if (!string.IsNullOrWhiteSpace(FilterTextBox.Text) &&
(!Regex.IsMatch(FilterTextBox.Text, "[^0-9]")))
{
_filterPlotReference = Convert.ToInt32(FilterTextBox.Text);
}
});
SetPlotList(_filterPlotReference);
FocusPlotItem(_focusPlotReference);
timerRunning = false; // reset it for next time use
}
P.S: I edited the other answer by adding (exactly) this answer, then I got rejected, the peer review says
This edit was intended to address the author of the post and makes no
sense as an edit. It should have been written as a comment or an
answer
I have no doubt that they did read the edit and evaluate it, not to mention the fact that it doesn't fit in a comment, so here I post it as an answer
Can you disable the timer until the RefreshPlotList function finishes?
May be at the start of the function disable the timer and at the end of RefreshPlotList function Enable the timer. I guess RefreshPlotList function is taking more than .5 seconds and another call is made before the current one is finished.

C# winforms GUI will not accept data from other threads

Below is a function I have running in a while(true) loop in a thread running a Winforms GUI.
I have a button set to put text data into the inBuffer object. this always works, however when I place into the buffer object from a different thread, the data is detected, pulled, and printed out in the Console.out.WriteLine statement, however it never shows up in the Display (textBox) object
public void put()
{
string strDisplayMe = ModemKind.MainClass.inBuffer.MkRequest();
if (strDisplayMe != "")
{
Console.Out.WriteLine("FOUND SOMETHING IN BUFFER: " + strDisplayMe);
char[] DisplayMeArr = strDisplayMe.ToCharArray ();
for (int i = 0; i <= DisplayMeArr.Length -1; ++i)
{
this.display.Text += DisplayMeArr [i];
Thread.Sleep (100);
}
this.display.Text += '\n';
}
}
EDIT: this is a separate class from what is feeding it data through the static buffer objects
Only the main window thread can access/change controls... if you want update the UI from the thread that runs the loop, you need to sync the call with the main thread using the Control.Invoke method.
For instance...
public void put()
{
string strDisplayMe = ModemKind.MainClass.inBuffer.MkRequest();
if (strDisplayMe != string.Empty)
{
char[] DisplayMeArr = strDisplayMe.ToCharArray();
for (int i = 0; i <= DisplayMeArr.Length -1; ++i)
{
this.UpdateUI(() => { this.display.Text += DisplayMeArr[i]; });
Thread.Sleep(100);
}
this.UpdateUI(() => { this.display.Text += '\n'; });
}
}
private void UpdateUI(Action handler)
{
this.Invoke(handler);
}
You can use MethodInvoker to access TextBox from other thread then GUI thread. Make a method to access the TextBox using MethodInvoker. you are assigning text multiple times consider assigning it once for performance, and use StringBuilder for string concatenation.
public void put()
{
string strDisplayMe = ModemKind.MainClass.inBuffer.MkRequest();
if (strDisplayMe != "")
{
Console.Out.WriteLine("FOUND SOMETHING IN BUFFER: " + strDisplayMe);
char[] DisplayMeArr = strDisplayMe.ToCharArray ();
for (int i = 0; i <= DisplayMeArr.Length -1; ++i)
{
AssignToTextBox(this.display, this.display.Text + DisplayMeArr [i]);
Thread.Sleep (100);
}
AssignToTextBox(this.display, this.display.Text + '\n');
}
}
void AssignToTextBox(TextBox txtBox, string value)
{
if(txtBox.InvokeRequired)
{
txtBox.Invoke(new MethodInvoker(delegate { txtBox.text = value; }));
}
}
Edit You can use BeginInvoke instead of Invoke to call it asynchronously. Read more about the Invoke and BeginInvoke in this question.
void AssignToTextBox(TextBox txtBox, string value)
{
txtBox.BeginInvoke(new Action(()=>txtBox.Text = value ));
}

How to update a label each time in for loop

I am working on a WinForm project where I have a label in a for loop. I want to show the label each time after executing the label.text statement. But it doesn't show for every time, rather it shows after for loop is finished.
I tried to achieve this by using Thread.Sleep(). But I can't. Please help me.
NOTE :- lblProgress is a Label
Here's my coding.
for (int i = 1; i <= sourceTable.Rows.Count - 1; i++)
{
string checkout;
checkout= sourceTable.Rows[i].Field<string>(0);
dest = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["local"].ConnectionString);
dest.Open();
destcmd = new SqlCommand(checkout, dest);
destcmd.ExecuteNonQuery();
dest.Close();
prcmail();
prcmessagecheck();
lblProgress.Text = "Hello World"+i;
Thread.Sleep(10000);
}
Whenever you create a WinForm application, it is spun up into a new process and a new thread is created. Any updates to the User Interface are all done on the same thread as your process. This means when your application is doing "busy work", your UI will be blocked because they are on the same thread. What this means is that, in order to achieve what it is you're trying to achieve, you have to do a little extra work.
First step we need to do is create a function for your work routine (we could use an anonymous function, but since you are new to C#, I think it'll be easier to understand if we break it out), like this:
private void DoWork()
{
for (int i = 1; i <= sourceTable.Rows.Count - 1; i++)
{
string checkout;
checkout= sourceTable.Rows[i].Field<string>(0);
dest = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["local"].ConnectionString);
dest.Open();
destcmd = new SqlCommand(checkout, dest);
destcmd.ExecuteNonQuery();
dest.Close();
prcmail();
prcmessagecheck();
lblProgress.Text = "Hello World"+i;
Thread.Sleep(1000); // I changed this from 10000 to 1000 (10 seconds down to 1 second)
}
}
Next, we need to create a new thread that executes our DoWork() function. Its unclear what the "trigger" is for doing your work, but I'm going to assume its a button click:
private void button1_click(object sender, EventArgs e)
{
var work = new Thread(DoWork);
work.Start();
}
So now, whenever someone click the button, we will start a new thread that executes our DoWork function in that thread. The new thread spawns, then execution is immediate returned and our GUI will now update in real time as our thread is executing in the background.
But wait! We still have one more problem to take care of. The problem is that Window's form controls are not thread safe and if we try to update a control from another thread, other then the GUI's thread, we will get a cross-thread operation error. The key to fixing this is to use InvokeRequired and Invoke.
First, we need to make another function that does just the label update:
private void SetProgressLabel(int progress)
{
lblProgress.Text = "Hello World" + progress;
}
In your form class, we also need to create a new delegate:
public partial class Form1 : Form
{
private delegate void ProgressCallback(int progress);
// ..
// The rest of your code
// ..
}
Finally, change your DoWork() method to something like this:
private void DoWork()
{
for (int i = 1; i <= sourceTable.Rows.Count - 1; i++)
{
string checkout;
checkout= sourceTable.Rows[i].Field<string>(0);
dest = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["local"].ConnectionString);
dest.Open();
destcmd = new SqlCommand(checkout, dest);
destcmd.ExecuteNonQuery();
dest.Close();
prcmail();
prcmessagecheck();
if (lblProgress.InvokeRequired)
{
lblProgress.Invoke(new ProgressCallback(SetProgressLabel), new object[] { i });
}
else
{
SetProgressLabel(i);
}
Thread.Sleep(1000); // I changed this from 10000 to 1000 (10 seconds down to 1 second)
}
}
This uses the label's (derived from Control) InvokeRequired property to determine if an Invoke is required. It returns true or false. If its false, we can just call our SetProgressLabel() function like we'd normally do. If its true, we must use Invoke to call our function instead.
Congratulations! You just made your first thread safe application.
Now, just as an aside note, you are not properly releasing and disposing of your objects. I recommend you change your DoWork() code to something like this:
private void DoWork()
{
for (int i = 1; i <= sourceTable.Rows.Count - 1; i++)
{
string checkout;
checkout = sourceTable.Rows[i].Field<string>(0);
using (dest = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["local"].ConnectionString))
{
dest.Open();
using (destcmd = new SqlCommand(checkout, dest))
{
destcmd.ExecuteNonQuery();
dest.Close();
prcmail();
prcmessagecheck();
if (lblProgress.InvokeRequired)
{
lblProgress.Invoke(new ProgressCallback(SetProgressLabel), new object[] { i });
}
else
{
SetProgressLabel(i);
}
Thread.Sleep(1000); // I changed this from 10000 to 1000 (10 seconds down to 1 second)
}
}
}
}
Because I wrapped your IDisposable's into using blocks, the resources will automatically be disposed of once it goes out of scope.
Although threading would be the more ideal solution another solution is:
Application.DoEvents()
this will give the UI thread time to update.
Example
for (int i = 1; i <= sourceTable.Rows.Count - 1; i++)
{
string checkout;
checkout= sourceTable.Rows[i].Field<string>(0);
dest = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["local"].ConnectionString);
dest.Open();
destcmd = new SqlCommand(checkout, dest);
destcmd.ExecuteNonQuery();
dest.Close();
prcmail();
prcmessagecheck();
lblProgress.Text = "Hello World"+i;
Application.DoEvents();
}
var ui = TaskScheduler.FromCurrentSynchronizationContext();
Task.Factory.StartNew(() =>
{
for (int i = 1; i <= sourceTable.Rows.Count - 1; i++)
{
string checkout;
checkout = sourceTable.Rows[i].Field<string>(0);
dest = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["local"].ConnectionString);
dest.Open();
destcmd = new SqlCommand(checkout, dest);
destcmd.ExecuteNonQuery();
dest.Close();
prcmail();
prcmessagecheck();
var task = Task.Factory.StartNew(() =>
{
//Thread.Sleep(1000);
lblProgress.Text = "Hello World" + i;
}, CancellationToken.None, TaskCreationOptions.None, ui);
task.Wait();
}
});
If you are executing the mentioned code on the UI thread, UI will be refreshed only after entire for loop is executed. Based on your needs, progress bar/background worker kind of set up looks suitable.

why do other events cannot be fired while "for loop" is in process?

I have a for loop and when the loop is being processed, I cant access any other function or event like clicking button it doesn't work till the for loop ends. Is there any way to overcome this Issue and hope I can get answer soon.
for (int i = 0; i < sizes - 2; i++)
{
if (pictureBox1.Image != null)
{
trackBar1.Value = trackBar1.Value + 1;
DisplayImage(_image);
}
}
Thanks in advance.
hi if you using framework 4.5
you can to the next :
Task.Run(() =>
{
for (int i = 0; i < sizes - 2; i++)
{
if (pictureBox1.Image != null)
{
trackBar1.Value = trackBar1.Value + 1;
DisplayImage(_image);
}
}
});
if not you can try this using thread :
Thread thread = new Thread(NewMethod);
thread.Start();
private void NewMethod()
{
for (int i = 0; i < sizes - 2; i++)
{
if (pictureBox1.Image != null)
{
trackBar1.Value = trackBar1.Value + 1;
DisplayImage(_image);
}
}
}
you can upgrade but you need to do it with delegate try this if you have cross thread operation error when update ui :
create delegate void function
delegate void Function();
then in your for make this :
Invoke(new Function(delegate()
{
label.text = "some text" ;
}));
This example shows how to create a new thread in .NET Framework. First, create a new ThreadStart delegate. The delegate points to a method that will be executed by the new thread. Pass this delegate as a parameter when creating a new Thread instance. Finally, call the Thread.Start method to run your method (in this case WorkThreadFunction) on background.
using System.Threading;
Thread thread = new Thread(new ThreadStart(WorkThreadFunction));
thread.Start();
The WorkThreadFunction could be defined as follows.
public void WorkThreadFunction()
{
try
{
// do any background work
}
catch (Exception ex)
{
// log errors
}
}

ThreadPool and displaying info without form freezing

I have one problem. In my project i need for more then 100 threads, that's why i prefer to use ThreadPool. here is a part of code, but in this case i have got a lot of memory usage and my form is very laggy, cuz of A lot of BeginInvoke calls(i suppose).
Is there any solutions for this problem?
public void launch()
{
while (data.Count > 0)
{
string[] part;
if (data.Count> 1000)
{
part = data.Take(1000).ToArray();
data = data.Skip(1000).ToList();
}
else
{
part = data.Take(data.Count).ToArray(); data = data.Skip(1000).ToList();
}
foreach (var input in part)
{
try
{
char splitter = ':';
if (input.Contains(';')) splitter = ';';
string login = input.Split(splitter)[0];
string pass = input.Split(splitter)[1];
EncryptCore ec = new EncryptCore(new byte[15]);
PacketSend ps = new PacketSend(ec, "");
ps._login = login;
ps._password = pass;
ps.Brutted+=ps_Parsed;
ps.Failed+=ps_Failed;
ThreadPool.QueueUserWorkItem(ps.Parse);
}
catch { Interlocked.Increment(ref curr); }
}
Thread.Sleep(1000);
}
data.Clear();
}
private void ps_Brutted(User Account)
{
toGet.Add(Account);
Interlocked.Increment(ref good);
goodLabl.BeginInvoke(new Action(delegate()
{
goodLabl.Text = "Good: " + good;
}));
Update();
}
private void Update()
{
try
{
Interlocked.Increment(ref curr);
progLabel.BeginInvoke(new Action(delegate()
{
progLabel.Text = (double.Parse(curr.ToString()) / double.Parse(max.ToString())).ToString("#%");
}));
progressBar.BeginInvoke(new Action(delegate()
{
progressBar.Text = (double.Parse(curr.ToString()) / double.Parse(max.ToString()) * 100).ToString("#");
}));
checkedLabl.BeginInvoke(new Action(delegate()
{
checkedLabl.Text = "Checked: " + curr + " / " + max;
}));
}
catch { }
}
So you have thousands of tasks, and each time one of them completes you update the UI by scheduling 4 updates on the UI thread. What you might consider doing is having the UI update on a timer-based schedule (try 100ms or 200ms) based on the integers that are updating.
Aside from that, you've got some strange numeric operations going on. You can just cast an int to a double, you don't have to round-trip through a String.

Categories

Resources