I'm trying to get this BackgroundWorker to work. When you click the View Orders button, it will display a message along the lines of "Retrieving new orders..." etc, and will do background work (mysql query), now, there's a bunch of stuff inside the DoWork method, and none of it gets done.
I know it's not because of the MySQL Query because it works fine on its own without the background worker.
Here's the code:
private void ViewOrders_Click(object sender, EventArgs e)
{
SlideTimer.Enabled = true;
Alert("Retrieving unconfirmed orders. Please wait.",
"Cancel",
Information,
true,
Color.FromArgb(63, 187, 249)
);
action = Action.ViewOrder;
bWorker.WorkerSupportsCancellation = true;
bWorker.DoWork += new DoWorkEventHandler(bWorker_DoWork);
bWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bWorker_RunWorkerCompleted);
bWorker.RunWorkerAsync();
}
void bWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
SlideTimer.Enabled = true;
Alert("All unconfirmed orders have been retrieved.",
"Dismiss",
Information,
true,
Color.FromArgb(63, 187, 249)
);
action = Action.None;
}
void bWorker_DoWork(object sender, DoWorkEventArgs e)
{
// Connect to Database, check for orders, and end.
if (bWorker.CancellationPending == true)
{
e.Cancel = true;
}
else
{
if (action == Action.ViewOrder)
{
thelist.Clear();
thelist.Visible = true;
thelist.BringToFront();
MessageBox.Show("");
thelist.Columns.Add("Order #");
thelist.Columns.Add("Name");
thelist.Columns.Add("E-mail Address");
thelist.Columns.Add("Delivery Address");
thelist.Columns.Add("Company");
thelist.Columns.Add("Phone Number");
// Check for new orders.
MySql.Data.MySqlClient.MySqlConnection msc = new MySql.Data.MySqlClient.MySqlConnection(cs);
try
{
msc.Open();
// Check for orders now.
string st = "SELECT DISTINCT(sessionid), firstname, lastname, email, streetaddress, suburb, postcode, state, company, phone FROM mysql_9269_dbase.order";
MySql.Data.MySqlClient.MySqlCommand cd = new MySql.Data.MySqlClient.MySqlCommand(st, msc);
MySql.Data.MySqlClient.MySqlDataReader msdr = cd.ExecuteReader();
while (msdr.Read())
{
if (thelist.Items.Count == 0)
{
ListViewItem LItem = new ListViewItem(msdr[0].ToString());
ListViewItem.ListViewSubItemCollection SubItems = new ListViewItem.ListViewSubItemCollection(LItem);
SubItems.Add(msdr[1].ToString() + " " + msdr[2].ToString());
SubItems.Add(msdr[3].ToString());
SubItems.Add(msdr[4].ToString() + " " + msdr[5].ToString() + " " + msdr[6].ToString() + " " + msdr[7]);
SubItems.Add(msdr[8].ToString());
SubItems.Add(msdr[9].ToString());
thelist.Items.Add(LItem);
thelist.Update();
}
else
{
sound.Play();
//status.Text = "Records found; Retrieving now.";
var found = false;
foreach (var item in thelist.Items)
{
if (item.ToString().Contains(msdr[0].ToString()))
found = true;
}
if (thelist.Items.Count == 0 || !found)
{
ListViewItem LItem = new ListViewItem(msdr[0].ToString());
ListViewItem.ListViewSubItemCollection SubItems = new ListViewItem.ListViewSubItemCollection(LItem);
SubItems.Add(msdr[1].ToString() + " " + msdr[2].ToString());
SubItems.Add(msdr[3].ToString());
SubItems.Add(msdr[4].ToString() + " " + msdr[5].ToString() + " " + msdr[6].ToString() + " " + msdr[7]);
SubItems.Add(msdr[8].ToString());
SubItems.Add(msdr[9].ToString());
thelist.Items.Add(LItem);
thelist.Update();
}
}
}
}
catch (Exception en)
{
Alert(en.Message,
"Retry",
Error,
true,
Color.FromArgb(249, 87, 55)
);
}
msc.Close();
}
thelist.Visible = true;
thelist.BringToFront();
}
}
private void MessageLink_Click(object sender, EventArgs e)
{
switch (MessageLink.Text)
{
case "Cancel":
bWorker.CancelAsync();
SlideTimer.Enabled = true;
Alert("You have successfully cancelled the current operation.",
"Dismiss",
Information,
true,
Color.FromArgb(63, 187, 249)
);
action = Action.None;
break;
case "":
break;
default:
break;
}
}
There's no errors or anything. Just that Nothing happens. What's causing the Background(so called)Worker to not DoWork()?
*Sorry for the lengthy code snip.
You've hooked up the callbacks but not actually called RunWorkerAsync to start it going.
As an aside, you're also calling UI elements in the DoWork method which will fail. You need to use BeginInvoke to mashal the updates back to the UI thread or do the updates in the RunWorkerComplete method (which is run on the UI thread automatically).
MessageBox.Show("");
This will cause a big problem.
You can't call UI from a non UI thread. I'm surprised that it hasn't raised an exception. At best it's probably causing your thread to abort and not do anything.
The theList looks like a UI element as well. If you are adding to control then you need to pass the data via an event to the UI so you can update it there.
You also have:
Alert(en.Message,
"Retry",
Error,
true,
Color.FromArgb(249, 87, 55)
);
In your exception handler. Again this looks like you are trying to call UI elements.
Related
My problem is that I have multiple Forms Controls that I need to make visible/invisible/change text, based on the output of my code.
Obviously this is very easy to achieve but the code is ridiculously long due to how I've set it up.
I have 3 image boxes containing a red, green and orange 'light'.
When the ping action is started (button click or a timer) all the controls need to be set like so:
// ping 1
redLight1.Visible = true;
greenLight1.Visible = false;
orangeLight1.Visible = false;
status_Lbl1.Text = "Initiated...";
I need to do this 9 times, and the code looks a bit meh to me having this repeated this many times.
I have a ping object that sends a ping every second for x amount of time. If all of the pings are sent and received successfully then an imagebox containing a green circle becomes visible greenLight1.Visible = true, while all others are set redLight1.Visible = false, orangeLight1.Visible = false, etc.
I have 9 of these sets of 'traffic lights', with a different IP being pinged and a different outcome for each.
I feel there must be a way to iteratively change the values of each of these boxes using the fact they all follow the same naming convention with just a different number on the end corresponding to the ping object they represent.
Here's a more visual idea of what I want to achieve.
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// int counter = 0
if (e.Cancelled == true)
{
status_Lbl1.Text = "Cancelled";
}
else if (e.Error != null)
{
status_Lbl1.Text = "Error: " + e.Error.Message;
}
else
{
foreach (Ping pingObj in pings)
{
if (pingObj.SuccessfulPings == 0)
{
Debug.WriteLine("Ping Object: " + pingObj.Fqdn + " failed to successfully ping");
// greenLight[i].Visible = false;
// orangeLight[i].Visible = false;
// redLight[i].Visible = true;
// counter++
}
else if (pingObj.FailedPings != 0)
{
Debug.WriteLine("Ping Object: " + pingObj.Fqdn + " failed to successfully ping: " + pingObj.FailedPings + " times.");
// greenLight[i].Visible = false;
// orangeLight[i].Visible = true;
// redLight[i].Visible = false;
// counter++
}
else
{
Debug.WriteLine("Ping Object: " + pingObj.Fqdn + " succesfully pinged: " + pingObj.SuccessfulPings + " times.");
// greenLight[i].Visible = false;
// orangeLight[i].Visible = false;
// redLight[i].Visible = false;
// counter++
}
}
}
}
Here's the method that creates/uses the ping objects just in case that is necessary
private async void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
try
{
// Create background worker
BackgroundWorker worker = (BackgroundWorker)sender;
// Write to log file
await file.WriteAsync("Starting job...\n");
await file.WriteAsync("Requested amount of pings: " + count + "\n");
// Create date object for logs
DateTime localDate = DateTime.Now;
for (int i = 0; i < count; i++)
{
// Create ping objects
System.Net.NetworkInformation.Ping pinger = new System.Net.NetworkInformation.Ping();
PingReply pingReply;
try
{
foreach (Ping pingObj in pings)
{
try
{
pingReply = pinger.Send(pingObj.IpAddress);
// Write log file
await file.WriteLineAsync(localDate.TimeOfDay + " | Friendly Name " + pingObj.FriendlyName + " | Ping: " + pingReply.Address + " | Status " + pingReply.Status + " | Time: " + pingReply.RoundtripTime);
if (pingReply.Status.ToString().Contains("Success"))
{
pingObj.SuccessfulPings += 1;
}
else // Unsuccessful ping has been sent
{
pingObj.FailedPings += 1;
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
}
wait(1000);
}
catch (Exception b)
{
Debug.WriteLine(b.ToString());
}
}
}
catch (Exception a)
{
Debug.WriteLine(a.ToString());
}
}
You can use Controls.Find() and "search by name" with the recurse option:
Control ctl = this.Controls.Find("greenLight" + counter, true).FirstOrDefault() as Control;
if (ctl != null) {
ctl.Visible = false;
}
I'm developing a sample program to connect multiple device using backgroundworker. Each device connected will be add to the list as new object. After finished connecting all the devices, i wanted to add an event handler for each connected devices. The problem that i'm facing now is the event handler doesn't firing at all. Below are the sample codes.
The Connect click button event :
private void btnConnect_Click(object sender, EventArgs e)
{
using (BackgroundWorker m_oWorker = new BackgroundWorker())
{
m_oWorker.DoWork += delegate (object s, DoWorkEventArgs args)
{
int iIpStart = 0;
int iIpEnd = 0;
string strIp1 = string.Empty;
string strIp2 = string.Empty;
list.Clear();
string[] sIP1 = txtIpStart.Text.Trim().ToString().Split('.');
string[] sIP2 = txtIpEnd.Text.Trim().ToString().Split('.');
iIpStart = Convert.ToInt32(sIP1[3]);
iIpEnd = Convert.ToInt32(sIP2[3]);
strIp1 = sIP1[0] + "." + sIP1[1] + "." + sIP1[2] + ".";
strIp2 = sIP2[0] + "." + sIP2[1] + "." + sIP2[2] + ".";
Ping ping = new Ping();
PingReply reply = null;
int iIncre = 0;
int iVal = (100 / (iIpEnd - iIpStart));
for (int i = iIpStart; i <= iIpEnd; i++)
{
Thread.Sleep(100);
string strIpconnect = strIp1 + i.ToString();
Console.Write("ip address : " + strIpconnect + ", status: ");
reply = ping.Send(strIpconnect);
if (reply.Status.ToString() == "Success")
{
if (ConnectDevice(strIpconnect))
{
strLastDevice = strIpconnect + " Connected";
isconnected = true;
}
else
{
isconnected = false;
}
}
else
{
isconnected = false;
}
m_oWorker.ReportProgress(iIncre);
iIncre = iIncre + iVal;
}
m_oWorker.ReportProgress(100);
};
m_oWorker.ProgressChanged += new ProgressChangedEventHandler(m_oWorker_ProgressChanged);
m_oWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(m_oWorker_RunWorkerCompleted);
m_oWorker.WorkerReportsProgress = true;
m_oWorker.WorkerSupportsCancellation = true;
m_oWorker.RunWorkerAsync();
}
}
ConnectDevice function method. Connected device will be added to the list :
protected bool ConnectDevice(string sIP)
{
try
{
NewSDK sdk = new NewSDK();
if (sdk.Connect() == true)
{
list.Add(new objSDK { sdk = sdk, ipaddress = sIP });
return true;
}
else
{
}
}
catch() {}
return false;
}
the Backgroundworker :
void m_oWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//If it was cancelled midway
if (e.Cancelled)
{
lblStatus.Text = "Task Cancelled.";
}
else if (e.Error != null)
{
lblStatus.Text = "Error while performing background operation.";
}
else
{
lblStatus.Text = "Task Completed...";
btnListen.Enabled = true;
}
}
void m_oWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
//Here you play with the main UI thread
progressBar1.Value = e.ProgressPercentage;
lblStatus.Text = "Processing......" + progressBar1.Value.ToString() + "%";
if (isconnected)
{
listBox2.Items.Add(strLastDevice);
string[] ssplit = sDeviceInfo.Split(';');
foreach (string sword in ssplit)
{
listBox1.Items.Add(sword);
}
}
}
The function to attached event :
private void RegisterEvent()
{
foreach (objSDK obj in list)
{
obj.sdk.OnTransaction += () =>
{
listBox1.Items.Add("ip : " + obj.IP + " transaction");
};
}
}
You have declared m_oWorker as a local variable. I'm guessing this was a mistake ( the m_ prefix should only be used for class member variables)?
Also, you declared it within a using statement, meaning that it that the framework will call Dispose() on it at the end of the using block. Even if you held on to a reference to it (and I don't think you do) it still means its resources will be deallocated, which is probably why it isn't handling any events.
I try another workaround by using thread and task and work perfectly. Thanks for all response
private bool ImportData()
{
bool result = false;
try
{
intdevid = int.Parse(cmbDeviceName.SelectedValue.ToString());
FetchDevicedata(intdevid);
//FTPTCompletedBatchTransfer();
FetchMaxReportId();
GetFTPFile(strDeviceIP, strDeviceUsername, strDevicePwd, strDevicePath + "//RunningBatch//RunningBatch.db", "RunningBatch.db"); // Copy RunningBatch.db to Debug Folder from Remote
LoadRunningData(); // Get Running Data in dataset from running.db
if (DecodeBatchData_R() == false)
{
MessageBox.Show("Running Batch Data Not Found");
}// save in batch master and row data table
GetFTPFile(strDeviceIP, strDeviceUsername, strDevicePwd, strDevicePath + "//CompletedBatch//CompletedBatch.db", "CompletedBatch.db");
LoadCompletedData();
if (DecodeBatchData() == false)
{
MessageBox.Show("Completed Batch Data not found");
}
result = true;
}
catch (Exception ex)\\here error:Cross-thread operation not valid: Control 'cmbDeviceName' accessed from a thread other than the thread it was created on.
{
clsLogs.LogError("Error: " + ex.Message + this.Name + " || ImportData");
result = false;
}
return result;
}
private void btnimport_Click(object sender, EventArgs e)
{
//////////////////copy checkweigher .db to database folder
dsCheckRptId = new DataSet();
///////////////////////////////////////////////////////////
if (cmbDeviceName.Text.ToString().Trim() == "--Select--")
{
MessageBox.Show("Please Select Proper Device");
cmbDeviceName.Focus();
return;
}
var deviceId = (int)cmbDeviceName.SelectedValue;
bgw.RunWorkerAsync(deviceId);
progressBar1.Visible = true;
label2.Visible = true;
}
void bgw_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1; i <= 100; i++)
{
var deviceId = (int)e.Argument;
e.Result = ImportData();
System.Threading.Thread.Sleep(100);
bgw.ReportProgress(i);
}
}
void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
label2.Text = String.Format("Progress: {0} %", e.ProgressPercentage);
}
void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
var result = (bool)e.Result;
if (cmbDeviceName.SelectedValue != null && cmbDeviceName.SelectedValue.ToString().Trim() != "0" && cmbDeviceName.SelectedValue.ToString().Trim() != "System.Data.DataRowView" && cmbDeviceName.SelectedValue.ToString().Trim() != "")
if (result)
{
MessageBox.Show("Data Import Completed Successfully for " + strDevicename);
clsLogs.LogEvent(3, "Data Import Completed Successfully for " + strDevicename);
}
else
{
MessageBox.Show("Data Import Fail For " + strDevicename);
clsLogs.LogEvent(3, "Data Import Fail for " + strDevicename);
}
progressBar1.Visible = false;
label2.Visible = false;
}
;When I run this background worker coding, there's an error stating "Cross-thread operation not valid: Control 'cmbDeviceName' accessed from a thread other than the thread it was created on. ."
How do I solve this problem guys?
WinForms controls are not thread safe, thus cross-thread operations on controls are not valid. You can access controls only from thread which created those controls. In your code you are accessing cmbDeviceName combobox from background thread. Best option to solve this is passing intdevid as RunWorkerAsync argument:
// executed on main thread
var deviceId = (int)cmbDeviceName.SelectedValue;
backgroundWorker.RunWorkerAsync(deviceId);
And get this argument in your DoWork handler:
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
// executed on background thread
var deviceId = (int)e.Argument;
// ...
}
Suggested reading: Safe, Simple Multithreading in Windows Forms
Ok, in my app there are times when loading the DataGridView can take a minute or two. What I want to do is show a GIF in a form with no border until it reaches the end of the loading function. However, if I do:
Views.Loading ldw = new Views.Loading();
ldw.Show();
...
ldw.Close();
...it never actually draws it to the screen and I can't see it. If I do ShowDialog(), it shows the window but never gets past that line of code. I have a feeling it's because it's not a background worker or because the focus gets set back to the parent because of processing...I don't know.
My form is a blank form, added a picture box, added a gif to the picture box, and made FormBorderStyle = none. Any and all help is appreciated.
Update: Current (non-working) Code
private void InitializeBackgroundWorker()
{
//Defines the DoWork Event Handler for _backgroundWorker.
_bgWorkerReports.DoWork += new DoWorkEventHandler(bgWorkerReports_DoWork);
//Defines the RunWorkCompleted Event Handler for _backgroundWorker.
_bgWorkerReports.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorkerReports_RunWorkerCompleted);
}
private void bgWorkerReports_DoWork(object sender, DoWorkEventArgs e)
{
ldw.Show();
try
{
string strFilter = "";
if (!_strSearchFilter.Equals(""))
{
strFilter += strFilter.Equals("") ? " " + _strSearchFilter : " and " + _strSearchFilter;
}
if (tvFigure.Nodes.Count > 0)
{
if (_strFigureFilter == "ALL")
{
strFilter += " " + Constants.GetColumnName("Figure") + " LIKE '%%' ";
}
else if (!_strFigureFilter.Equals("") && !_strFigureFilter.Equals(tvFigure.TopNode.Name))
{
if (_strSearchFilter.Equals("") || !cbCurrentFigure.Checked)
{
strFilter += strFilter.Equals("") ? " " + Constants.GetColumnName("Figure") + "='" + _strFigureFilter + "'" : " and " + Constants.GetColumnName("Figure") + "='" + _strFigureFilter + "'";
}
}
}
if (!_strIndentureFilter.Equals(""))
{
strFilter += strFilter.Equals("") ? " " + _strIndentureFilter : " and " + _strIndentureFilter;
}
if (!_strReportFilter.Equals(""))
{
strFilter += (!strFilter.Equals("") ? " and" : "") + " part_id in (" + _strReportFilter + ")";
}
if (strFilter.Length > 0)
{
BindingSource bSource = new BindingSource();
bSource.DataSource = _dataController.PopulateDataGrid(_nViewMode, strFilter).Tables[0];
//Set DataSource to bindingSource for DataGridView.
if (_lstValidationResults.Count > 0)
{
dgvParts.DataSource = _lstValidationResults;
foreach (DataGridViewColumn dc in dgvParts.Columns)
{
dc.DataPropertyName = "ErrorMessage";
dc.Visible = true;
dc.SortMode = DataGridViewColumnSortMode.Programmatic;
dc.AutoSizeMode = DataGridViewAutoSizeColumnMode.ColumnHeader;
}
dgvParts.AutoResizeColumns();
return;
}
else if (!string.IsNullOrEmpty(_strFigureFilter))
{
dgvParts.DataSource = bSource;
dgvParts.Columns[0].Visible = false;
dgvParts.Columns["Description"].Resizable = DataGridViewTriState.False;
dgvParts.Columns["Description"].Width = 750;
}
// Automatically resize the visible rows.
foreach (DataGridViewColumn col in dgvParts.Columns)
{
col.SortMode = DataGridViewColumnSortMode.Automatic;
if (col.Name != "Description")
{
dgvParts.AutoResizeColumn(col.Index);
}
}
dgvParts.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCells;
// Hide the ToolTips for all the cells - redisplay if there is a report.
dgvParts.ShowCellToolTips = true;
// Set the dataGridView control's border.
dgvParts.BorderStyle = BorderStyle.Fixed3D;
// Get and set the ipb_number to the label.
string ipb_number = _dataController.IPBNumber;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void bgWorkerReports_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
ldw.Close();
this.Cursor = Cursors.Default; //Throws error (Cross-thread)
FormatCells();
BuildColumnsComboBox();
int nTotalCount = 0;
foreach (ListViewItem lvi in listView1.Items)
{
int nCount = _lstReportRecords.Where(rr => lvi.Text.Contains(rr.Description)).Count();
nTotalCount += nCount;
lvi.Text = (lvi.Text.Contains("(") ? lvi.Text.Substring(0, lvi.Text.IndexOf("(") + 1) : lvi.Text.Trim() + " (") + nCount.ToString() + ")";
}
rbAllReports.Text = (rbAllReports.Text.Contains("(") ? rbAllReports.Text.Substring(0, rbAllReports.Text.IndexOf("(") + 1) : rbAllReports.Text + " (") + nTotalCount.ToString() + ")";
int nTaggedCount = _lstReportRecords.Where(rr => rr.Description.Contains("Tagged")).Count();
rbTaggedRecords.Text = (rbTaggedRecords.Text.Contains("(") ? rbTaggedRecords.Text.Substring(0, rbTaggedRecords.Text.IndexOf("(") + 1) : rbTaggedRecords.Text + " (") + nTaggedCount.ToString() + ")";
}
Ideally you would have two threads: the GUI thread and the working thread (which can be a BackgroundWorker). Create and show the window in the GUI thread. Handle the loading in the BackgroundWorker's DoWork event. When the loading is done you can call Close() on the load window from the RunWorkerCompleted event and dispose of it.
LoadWindow loadWindow = new LoadWindow();
loadWindow.TopMost = true; // make sure it doesn't get created behind other forms
loadWindow.Show();
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
worker.RunWorkerAsync();
void worker_DoWork(object sender, DoWorkEventArgs e)
{
// do your loading here
}
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// set DataGridView datasource here
...
// close loading window
loadWindow.Close();
}
The problem you might have with displaying the window could be from the TopMost property, which must be set to true. You can also try calling BringToFront() on the loading window after you've created and shown it.
Yes, BackgroundWorker is for exactly this type of purpose. A couple things to add:
Do not interact with the UI in the worker_DoWork event as it is running on a background thread. Set e.Result when you're finished, which you can check from the RunWorkerCompleted event - or use a form-level variable.
Let any exceptions fall through in the worker_DoWork event and you will see them in the worker_RunWorkerCompleted event in e.Error.
If you need the ability to cancel your load, set worker.WorkerSupportsCancellation and check the e.Cancel while in your DoWork event, then you can check e.Cancelled in your RunWorkerCompleted event.
You should call .Dispose() on your BackgroundWorker when finished.
You'll have to run the code to fill the grid on another thread. Something like:
// Set the picturebox loading state, resize the form etc.
PictureBox.SetLoadingImage();
// Initialize a new thread
Thread t = new Thread(new ThreadStart(() =>
{
// Fill the gridview here
GridView1.DataSource = FillWithData();
GridView1.DataBind();
// When finished, reset the picturebox on it's own thread
PictureBox.Invoke((MethodInvoker)(()=> PictureBox.ClearLoadingImage() ));
}));
// Run the thread.
t.Start();
I have a CopyFile and Directory project. But when I started to copy Gui, it freezes. I can't do anything with file copying. So I found my solution at BackgroundWorker Component. But I have a problem with this component too.
There are 3 radio buttons and command button. When I click the command button, it's checking if radiobutton1 is checked or else if radiobutton2 checked or else if radiobutton3 is checked. If radiobutton1 is checked, do a lot things, or if radiobutton2 checked, do another thing, etc. There are 3 backgroundworkers for 3 radiobuttons. When I checked radiobutton1, backgroundworker1 dowork event working. When I checked radiobutton2, backgroundworker2 dowork event working. etc...
My problem is when I checked radiobutton1 and click commmand button. Starting backgroundworker1 do work event but it's also continuing to control if radiobutton2 is checked or not. It is not stopping, so I am getting errors. My code is below:
private void button1_Click(object sender, EventArgs e)
{
if (radioButton1.Checked)
{
backgroundWorker1.RunWorkerAsync();
}
if (radioButton2.Checked)
{
StreamReader sr = new StreamReader(Application.StartupPath + #"\hakimler.txt");
while ((satir = sr.ReadLine()) != null)
{
try
{
bool copy = CopyDirectory(DosyaYolu.kaynak, #"\\" + satir + #"" + DosyaYolu.hedef, true);
if (copy)
{
kopya += 1;
}
else
{
sw.WriteLine(satir);
}
}
catch (Exception)
{
}
}
sw.Close();
MessageBox.Show("İşlem tamamlandı", "İşlem Sonu", MessageBoxButtons.OK, MessageBoxIcon.Information);
lblkopya.Text = "Başarıyla tamamlanan iş sayısı : " + kopya.ToString();
return;
}
if (chkPersonel.Checked == true)
{
StreamReader sr = new StreamReader(Application.StartupPath + #"\personel.txt");
while ((satir = sr.ReadLine()) != null)
{
try
{
bool copy = CopyDirectory(DosyaYolu.kaynak, #"\\ab04500-" + satir + #"" + DosyaYolu.hedef, true);
//bool copy = CopyDirectory(Application.StartupPath + #"\TELEFON REHBERİ", #"\\" + satir + #"\c$\Documents and Settings\All Users\Start Menu", true);
if (copy)
{
kopya += 1;
}
else
{
sw.WriteLine(satir);
}
}
catch (Exception)
{
}
}
sw.Close();
MessageBox.Show("İşlem tamamlandı", "İşlem Sonu", MessageBoxButtons.OK, MessageBoxIcon.Information);
lblkopya.Text = "Başarıyla tamamlanan iş sayısı : " + kopya.ToString();
return;
}
else
{
if (txtBilgisayar.Text == "" && txtDongu.Text == "")
{
MessageBox.Show("Boşlukları dolduralım bi zahmet :#", "Bilgisayar Kodlarını girelim lütfen!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
bilgisayar = Convert.ToInt32(txtBilgisayar.Text);
dongu = Convert.ToInt32(txtDongu.Text);
for (int i = bilgisayar; i <= dongu; i++)
{
try
{
bool copy = CopyDirectory(DosyaYolu.kaynak, #"\\ab04500-" + bilgisayar + #"" + DosyaYolu.hedef, true);
if (copy)
{
kopya += 1;
}
else
{
sw.WriteLine(satir);
}
}
catch (Exception)
{
}
if (i == dongu)
{
sw.Close();
MessageBox.Show("İşlem tamamlandı", "İşlem Sonu", MessageBoxButtons.OK, MessageBoxIcon.Information);
lblkopya.Text = "Başarıyla tamamlanan iş sayısı : " + kopya.ToString();
}
bilgisayar += 1;
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
sw = new StreamWriter(DateTime.Today.ToShortDateString().ToString() + "_ulasmayanlar.txt", true);
StreamReader sr = new StreamReader(Application.StartupPath + #"\savcilar.txt");
while ((satir = sr.ReadLine()) != null)
{
try
{
bool copy = CopyDirectory(DosyaYolu.kaynak, #"\\" + satir + #"" + DosyaYolu.hedef, true);
//bool copy = CopyDirectory(Application.StartupPath + #"\TELEFON REHBERİ", #"\\" + satir + #"\c$\Documents and Settings\All Users\Start Menu", true);
if (copy)
{
kopya += 1;
}
else
{
sw.WriteLine(satir);
}
}
catch (Exception)
{
}
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
sw.Close();
MessageBox.Show("İşlem tamamlandı", "İşlem Sonu", MessageBoxButtons.OK, MessageBoxIcon.Information);
lblkopya.Text = "Başarıyla tamamlanan iş sayısı : " + kopya.ToString();
}
its control if radiobutton1 chechked or not if its checked true its start bgworkers do work event and its going to continue if radiobutton2 checked or not if radiobutton3 checked or not blabla its not stopping when its see radiobutton1 checked true.
yes i want to stop controlling the another radiobutton's chechked true or not.if radiobutton1's chechked is true only do backgroundworkers dowork event and STOP.
I'm not quite sure what your problem exactly is, but in your code if your radioButton1 is
Checked then the Background worker will do it's thing, else it won't.
Isn't that what you want?
I don't see any code for other radio buttons you mention.
Ah, so you want to stop the background workers when you check antoher radio button?
In your dowork() method you'll have to check if bg.CancellationPending == true and exit the method if it is.
Also you have to set WorkerSupportsCancellation to true after you initialize the BG worker.