So i have the following code:
public void tViewers(int? start, int? stop)
{
for (int? i0 = start; i0 <= stop; i0++)
{
StartLabel:
Viewer v = new Viewer(channelNameTextBox.Text, this);
if (urlWithTokens.Contains(v.getViewerLink()))
{
goto StartLabel;
}
else
{
if (v.getViewerLink() != "")
{
Console.WriteLine("[V #" + i0 + "] SUCCESS");
urlWithTokens.Add(v.getViewerLink());
}
else
{
Console.WriteLine("Channel not found.");
showError("The channel name is not valid.", true);
this.Invoke(new Action(() => this.botControlls.Enabled = true));
urlWithTokens.Clear();
}
}
v = null; // clear
}
Console.WriteLine("[V] " + start + " to " + stop + " COMPLETED");
start = null;
stop = null;
GC.SuppressFinalize(this);
}
Which is executed by:
for (int i = 0; i < maxThreads; i++)
{
taskFactory.StartNew(() => tViewers(someValue, someHigherValue));
}
The problem here is the local parameters "start" and "stop" in tViwers and it returst some stange values.
fx if i print "start" it should return the "someValue" and "someHigherValue" depending on what "thread" it is running in, however it returns strange values 40, 50 or something (even if it should return 1, 2, 3...
I have tried using the GC.SuppressFinalize(this); and setting the int's to null my allowing them to be null (int?). However the problem is still there...
Can someone help me?
Related
This question already has answers here:
C# - Read in a large (150MB) text file into a Rich Text Box
(2 answers)
Closed 1 year ago.
I have a large text files for example 39000 lines and above , i want to load it into richtextbox , using normal way like this:
Richtextbox1.Text=File.ReadAllLines(file);
or
Richtextbox1.LoadFile(...);
it take long time and freeze the UI even i use BackgroundWorker, so i decide to split file into parts each part is 1000 lines and append them to the richtextbox , i mean i read 1000 lines from file into string and then append it to the richtextbox, here is my code:
private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
StreamReader reader = null;
try
{
//
int ProgressPercentage = 0;
//enable stop Correct button
BTN_Send_Ref.Invoke((MethodInvoker)(() =>
{
BTN_Send_Ref.Enabled = true;
}));
string[] Lines = File.ReadAllLines(InputTextFile);
//MessageBox.Show("Lines : " + Lines.Length);
int i= 0;
int j = 0;
string LinesCollection = "";
while (true)
{
if (worker.CancellationPending)
{
if (reader != null)
{
reader.Close();
reader = null;
}
e.Cancel = true;
//cancel backgroundworker
return;
}
LinesCollection = "";
if (i > Lines.Length ||
j >= Lines.Length)
{
break;
}
i += 1000;
if (i >= Lines.Length)
{
i = Lines.Length ;
}
while ( j < i)
{
if (worker.CancellationPending)
{
if (reader != null)
{
reader.Close();
reader = null;
}
e.Cancel = true;
//cancel backgroundworker
return;
}
if (j < Lines.Length)
{
if (LinesCollection == "")
{
LinesCollection = Lines[j];
}
else
{
LinesCollection += Environment.NewLine + Lines[j];
}
}
ProgressPercentage = (int)Math.Round((((double)j) / Lines.Length) * 100);
if (ProgressPercentage < 100)
{
//report progress
worker.ReportProgress(ProgressPercentage);
}
ProgressPercentage++;
j++;
}
RichTXT_OutText_Ref.Invoke((MethodInvoker)(() =>
{
RichTXT_OutText_Ref.AppendText(LinesCollection +Environment.NewLine);
}));
LBL_CountOfChars_Ref.Invoke((MethodInvoker)(() =>
{
LBL_CountOfChars_Ref.Text = "(" + RichTXT_OutText_Ref.Text.Length + ") Char";
LBL_CountOfChars_Ref.Update();
}));
LBL_CountOfLines_Ref.Invoke((MethodInvoker)(() =>
{
LBL_CountOfLines_Ref.Text = "(" + RichTXT_OutText_Ref.Lines.Length + ") Line";
LBL_CountOfLines_Ref.Update();
}));
}
/*int Tmp_Count = 0;
if (RichTXT_OutText_Ref.InvokeRequired)
{
RichTXT_OutText_Ref.Invoke((MethodInvoker)(() =>
{
RichTXT_OutText_Ref.LoadFile(InputTextFile, RichTextBoxStreamType.PlainText);
}));
}
else
{
RichTXT_OutText_Ref.LoadFile(InputTextFile, RichTextBoxStreamType.PlainText);
}
LBL_CountOfChars_Ref.Invoke((MethodInvoker)(() =>
{
LBL_CountOfChars_Ref.Text = "(" + RichTXT_OutText_Ref.Text.Length + ") Char";
LBL_CountOfChars_Ref.Update();
}));
LBL_CountOfLines_Ref.Invoke((MethodInvoker)(() =>
{
LBL_CountOfLines_Ref.Text = "(" + RichTXT_OutText_Ref.Lines.Length + ") Line";
LBL_CountOfLines_Ref.Update();
}));
*/
/*reader= File.OpenText(InputTextFile);
string Line = "";
int LinesCounter = 0;
while ((Line = reader.ReadLine()) != null)
{
if (worker.CancellationPending)
{
if (reader != null)
{
reader.Close();
reader = null;
}
e.Cancel = true;
//cancel backgroundworker
return;
}
if(LinesCounter >0 && LinesCounter <= 1000)
{
RichTXT_OutText_Ref.Invoke((MethodInvoker)(() =>
{
RichTXT_OutText_Ref.AppendText(LinesCollection);
}));
LinesCollection = "";
LinesCounter = 0;
}
else
{
if (LinesCollection == "")
{
LinesCollection= Line;
}
else
{
LinesCollection += Environment.NewLine + Line;
}
}
LBL_CountOfChars_Ref.Invoke((MethodInvoker)(() =>
{
LBL_CountOfChars_Ref.Text = "(" + RichTXT_OutText_Ref.Text.Length + ") Char";
LBL_CountOfChars_Ref.Update();
}));
LBL_CountOfLines_Ref.Invoke((MethodInvoker)(() =>
{
LBL_CountOfLines_Ref.Text = "(" + RichTXT_OutText_Ref.Lines.Length + ") Line";
LBL_CountOfLines_Ref.Update();
}));
//calculate progress value
ProgressPercentage = (int)Math.Round((((double)PercentageCounter) / Lines.Length) * 100);
if (ProgressPercentage < 100)
{
//report progress
worker.ReportProgress(ProgressPercentage);
}
TempCount++;
PercentageCounter++;
Tmp_Count++;
}
*/
if (reader != null)
{
reader.Close();
reader = null;
}
//disable Correct button because
//we are out of loop
if (BTN_Send_Ref != null)
{
//we call this btn Correct
//from another thread
//so we must use Invoke
BTN_Send_Ref.Invoke((MethodInvoker)(() =>
{
BTN_Send_Ref.Enabled = false;
}));
}
}
catch (Exception ex)
{
if (reader != null)
{
reader.Close();
reader = null;
}
MessageBox.Show(ex.Message+"\n"+ex.StackTrace.ToString());
throw ex;
}
}
the problem is that the code work fine with some file say less than 1000 but when i use large file has size greater than 1000,the count of lines is less than actual file lines
for example i attach text file
my text file
which has size 62077 but the after use my code the richtextbox lines is 62028, and count of characters also is less the actual count of characters of file, but the start and the end of content in richtextbox and file are the same, i do not know where is the error, all i want is to read text file , combine every 1000 lines in one string append it the richtextbox repeat the operation until end of file content.
i do not want to use Richtextbox1.LoadFile(...)and Richtextbox1.Text=File.ReadAllLines(file); because they freeze and hung the UI this happen when using large files more than 39000 lines,
i want to know what is the wrong with code?why dose not get right result?
i hope you help me.
i use this code and it work fine:
private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
try
{
//
int ProgressPercentage = 0;
BTN_Send_Ref.Invoke((MethodInvoker)(() =>
{
BTN_Send_Ref.Enabled = true;
}));
string[] Lines = File.ReadAllLines(InputTextFile);
string LinesCollection = "";
for(int x = 0; x < Lines.Length; x++)
{
if (worker.CancellationPending)
{
e.Cancel = true;
//cancel backgroundworker
return;
}
LinesCollection += Lines[x] + Environment.NewLine;
if (x>0 && x % 1000 == 0)
{
RichTXT_OutText_Ref.Invoke((MethodInvoker)(() =>
{
RichTXT_OutText_Ref.AppendText(LinesCollection );
}));
LinesCollection = "";
LBL_CountOfChars_Ref.Invoke((MethodInvoker)(() =>
{
LBL_CountOfChars_Ref.Text = "(" + RichTXT_OutText_Ref.Text.Length + ") Char";
LBL_CountOfChars_Ref.Update();
}));
LBL_CountOfLines_Ref.Invoke((MethodInvoker)(() =>
{
LBL_CountOfLines_Ref.Text = "(" + RichTXT_OutText_Ref.Lines.Length + ") Line";
LBL_CountOfLines_Ref.Update();
}));
}
if(x==Lines.Length-1 && LinesCollection != "")
{
RichTXT_OutText_Ref.Invoke((MethodInvoker)(() =>
{
RichTXT_OutText_Ref.AppendText(LinesCollection.TrimEnd(Environment.NewLine.ToCharArray()) );
}));
LinesCollection = "";
LBL_CountOfChars_Ref.Invoke((MethodInvoker)(() =>
{
LBL_CountOfChars_Ref.Text = "(" + RichTXT_OutText_Ref.Text.Length + ") Char";
LBL_CountOfChars_Ref.Update();
}));
LBL_CountOfLines_Ref.Invoke((MethodInvoker)(() =>
{
LBL_CountOfLines_Ref.Text = "(" + RichTXT_OutText_Ref.Lines.Length + ") Line";
LBL_CountOfLines_Ref.Update();
}));
}
ProgressPercentage = (int)Math.Round((((double)x) / Lines.Length) * 100);
if (ProgressPercentage < 100)
{
//report progress
worker.ReportProgress(ProgressPercentage);
}
}
//disable Correct button because
//we are out of loop
if (BTN_Send_Ref != null)
{
BTN_Send_Ref.Invoke((MethodInvoker)(() =>
{
BTN_Send_Ref.Enabled = false;
}));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message+"\n"+ex.StackTrace.ToString());
throw ex;
}
}
The problem with the following code is :
even if I only have 10 locations to deliver and one depot set at location 0 , in this example, vehicles 1,2,3,4 seem to have they're depot at locations 10,11,12,13. Those locations don't exists. The 10 that I have are numbered from 0-9.
On the other hand the business logic seems to be OK :
as I isolated the cost of leaving the depot and the one of going back to it ( value 10 ) I get the expected result : 104. There are only 4 trips between cities that don't include the depot.
Is this a bug in Google or-tools ?
public static void Main(string[] args)
{
new CVRP().Solve(10);
}
private class RandomManhattan : NodeEvaluator2
{
public override long Run(int first_index, int second_index)
{
if (first_index == 0 || second_index == 0)
return 10;
return 1;
}
};
private class Demand : NodeEvaluator2
{
public override long Run(int first_index, int second_index)
{
return 1;
}
};
private void Solve(int locations)
{
var nr_vehicle = 5;
var routing = new RoutingModel(locations, nr_vehicle, new[] {0, 0, 0, 0, 0}, new[] {0, 0, 0, 0, 0});
Console.WriteLine("Depot : " + routing.GetDepot());
NodeEvaluator2 demandCallback = new Demand();
routing.AddDimension(demandCallback, 0, 3, true, "capacity");
var distances = new RandomManhattan();
routing.SetCost(distances);
var searchParameters =
RoutingModel.DefaultSearchParameters();
searchParameters.FirstSolutionStrategy =
FirstSolutionStrategy.Types.Value.PathCheapestArc;
var solution = routing.SolveWithParameters(searchParameters);
if (solution != null)
{
var output = "Total cost: " + solution.ObjectiveValue() + "\n";
// Dropped orders
var dropped = "";
for (var order = 0; order < locations; ++order)
{
if (solution.Value(routing.NextVar(order)) == order)
{
dropped += " " + order;
}
}
if (dropped.Length > 0)
{
output += "Dropped orders:" + dropped + "\n";
}
// Routes
for (var vehicle = 0; vehicle < nr_vehicle; ++vehicle)
{
var route = "Vehicle " + vehicle + ": ";
var order = routing.Start(vehicle);
if (routing.IsEnd(solution.Value(routing.NextVar(order))))
{
route += "Empty";
}
else
{
for (; !routing.IsEnd(order); order = solution.Value(routing.NextVar(order)))
{
var local_load = routing.CumulVar(order, "capacity");
route += order + " Load(" + solution.Value(local_load) + ") -> ";
}
if (route.Length > 0)
route = route + "0";
}
output += route + "\n";
}
Console.WriteLine(output);
}
}
You have to wrap order in
route += order + " Load(" + solution.Value(local_load) + ") -> ";
inside model.IndexToNode(order), like this
route += model.IndexToNode(order) + " Load(" + solution.Value(local_load) + ") -> ";
I'm in my second quarter of c # programming and i'm working on a POS application. I have my windows form created and I have my basic code done for the first week it was assigned. Now I have to "idiot-proof" my code by making sure that only correct data can be entered. Here's what I have so far:
private void btnAddItem_Click(object sender, EventArgs e)
{
//Declare variables
double dblSalesTax = 0, dblPrice, dblTax, dblSalesPrice;
string strItem, strTaxAdded;
int intQuantity;
bool diffTest = false;
//Process user input
while (!diffTest)
{
diffTest = double.TryParse(txtSalesTax.Text, out dblSalesTax);
}
while (dblSalesTax < 0 || dblSalesTax > 25)
{
MessageBox.Show("Please enter a valid tax.");
txtSalesTax.Clear();
diffTest = false;
}
intQuantity = Convert.ToInt16(txtQuantity.Text);
dblPrice = Convert.ToDouble(txtPrice.Text);
dblSalesPrice = dblPrice * intQuantity;
strItem = cbxItem.Text;
intQuantity = Convert.ToInt16(txtQuantity.Text);
dblSubtotal += dblSalesPrice;
if (chkTaxExempt.Checked)
{
dblTax = 0;
strTaxAdded = "";
}
else
{
dblTax = dblSalesPrice * dblSalesTax;
strTaxAdded = "*";
}
dblTaxTotal += dblTax;
lbxTally.Items.Add(strItem + ", " + dblSalesPrice.ToString("C") + strTaxAdded);
//Reset Form
txtPrice.Clear();
txtQuantity.Clear();
chkTaxExempt.Checked = false;
cbxItem.Focus();
}
private void btnEndSale_Click(object sender, EventArgs e)
{
dblGrandTotal = dblSubtotal + dblTaxTotal;
lbxTally.Items.Add("");
lbxTally.Items.Add("");
lbxTally.Items.Add("Subtotal: " + dblSubtotal.ToString("C"));
lbxTally.Items.Add("Tax Total: " + dblTaxTotal.ToString("C"));
lbxTally.Items.Add("Grand Total: " + dblGrandTotal.ToString("C"));
}
private void btnPay_Click(object sender, EventArgs e)
{
double dblPay, dblChange;
dblPay = Convert.ToDouble(txtPay.Text);
dblChange = dblPay - dblGrandTotal;
lbxTally.Items.Add("");
lbxTally.Items.Add("Amount Paid: " + dblPay.ToString("C"));
lbxTally.Items.Add("Change: " + dblChange.ToString("C"));
}
Variables being declared beforehand and diffTest being initialized as false.
The assignment is to make sure that the sales tax entered is between 0 and 25 and that they can't enter words or anything else. I thought I did it right but when I run it, I have an infinite loop on my message box and I can't figure out how to get out of it correctly (entering break just gets me out but keeps the input). I have google'd to my hearts content but haven't found a solution but I feel like it's because my code is reusing what's in the text box automatically (I could be very wrong!). Once I get this i'll have to "idiot-proof" my other inputs but I haven't tried yet cause I'm still stuck on this first one. I'm a beginner programming student so any help is appreciated.
You don't need a while statement there. Change it to:
if (dblSalesTax < 0 || dblSalesTax > 25)
Because you have there a while loop as soon as you step into that loop you will never get out because your condition will be always true.
My guess is that you should change While to If.
private void btnAddItem_Click(object sender, EventArgs e)
{
//Declare variables
double dblSalesTax = 0, dblPrice, dblTax, dblSalesPrice;
string strItem, strTaxAdded;
int intQuantity;
bool diffTest = false;
//Process user input
//While (!diffTest)
//{
diffTest = double.TryParse(txtSalesTax.Text, out dblSalesTax);
//}
// Check if the value gets parsed and is in range, otherwise show error and
//exit from this handler
If (!diffTest || dblSalesTax < 0 || dblSalesTax > 25) '<--- Change While to If
{
MessageBox.Show("Please enter a valid tax.");
txtSalesTax.Clear();
diffTest = false;
return; // Return from here since validation failed
}
...
...
...
}
May you can try using Parallel.Invoke(() => DoSomeWork(), () => DoSomeOtherWork()); withawait for the the task that has your loop, something like below:
Parallel.Invoke(
() =>
{
Console.WriteLine("Begin first task...");
}, // close first Action
async () =>
{
Console.WriteLine("Begin second task...");
while (true)
{
// HERE you are the code you need to be executed in infinite loop
await Task.Delay(60000);
}
}, //close second Action
() =>
{
Console.WriteLine("Begin third task...");
} //close third Action
); //close parallel.invoke
Console.WriteLine("Returned from Parallel.Invoke");
I want the for loop to continue execution if an exception occurs (99 out of 100, wiil be conection problem to portal), meaning move to connecting to next portal.
I thought using I finally compined with a goto but I dislike using goto.
for (int i = 0; i < Portals.Count; i++)
{
try
{
if (!Portals[i].IsConnected)
{
Portals[i].Connect();
///..Permorm variours actioms...
}
}
catch
{
Window7 win = new Window7();
win.label1.Content = "Connect to Portal " + (i + 1).ToString() + " Failed..";
win.ShowDialog();
return;
}
If you wish to continue with the code placed after the try/catch use this :
(simply remove the return; statement)
for (int i = 0; i < Portals.Count; i++)
{
try
{
if (!Portal[i].IsConnected)
{
Portal[i].Connect();
///..Permorm variours actioms...
}
}
catch
{
Window7 win = new Window7();
win.label1.Content = "Connect to Portal " + (i + 1).ToString() + " Failed..";
win.ShowDialog();
}
// TODO - Some more code here
}
If you wish to stop that iteration if an Exception occurs, simply replace your return by a continue :
for (int i = 0; i < Portals.Count; i++)
{
try
{
if (!Portal[i].IsConnected)
{
Portal[i].Connect();
///..Permorm variours actioms...
}
}
catch
{
Window7 win = new Window7();
win.label1.Content = "Connect to Portal " + (i + 1).ToString() + " Failed..";
win.ShowDialog();
continue;
}
// TODO - Some more code here
}
I have a .NET Winforms-based program I wrote in C# where I programmatically select text within a TextBox using the Select() method. I can see the selected text on the screen and the SelectionLength member reports an accurate amount of selected characters, but the SelectedText member doesn't contain any text:
int indexPeriod = strLectureText.IndexOfAny(terminators, indexStart);
thisTextbox.Focus();
if (indexPeriod > -1)
{
thisTextbox.Select(indexStart, (indexPeriod - indexStart) + 1);
}
else
{
thisTextbox.Select(indexStart, thisTextbox.Text.Length);
}
Log.Debug("jtext len=" + thisTextbox.SelectionLength + " txt=" + thisTextbox.SelectedText);
thisTextbox.ScrollToCaret();
What's going on?
Update Nov 16 2013
I am adding additional code per #KingKing's request:
delegate void delegateMoveToNextTextFragment(ref TextBox thisTextbox, char[] terminators);
private void MoveToNextTextFragment(ref TextBox thisTextbox, char[] terminators)
{
string strLectureText = String.Empty;
strLectureText = thisTextbox.Text;
int currentStartPos = thisTextbox.SelectionStart + thisTextbox.SelectionLength - 1
// search the rest of the buffer after the currently-selected string to find the next period
int skipLastChar = 0;
// don't include last selected character in search
try
{
if ((thisTextbox.SelectionLength > 0) & (strLectureText[currentStartPos] != '.'))
{
skipLastChar = 1;
}
}
catch (Exception ex)
{
Debug.WriteLine("exception caught! ex=" + ex.Message);
skipLastChar = 0;
}
int indexStart = 0;
if (currentStartPos == 0)
{
indexStart = 0;
}
else
{
indexStart = currentStartPos + 1;
}
int indexPeriod = strLectureText.IndexOfAny(terminators, indexStart);
if (indexPeriod > -1)
{
thisTextbox.Select(indexStart, (indexPeriod - indexStart) + 1);
}
else
{
thisTextbox.Select(indexStart, thisTextbox.Text.Length);
}
thisTextbox.Focus();
Log.Debug("jtext len=" + thisTextbox.SelectionLength + " txt=" + thisTextbox.SelectedText);
thisTextbox.ScrollToCaret();
}