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.
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
In the top of the form1 i added:
System.Threading.ManualResetEvent _busy = new System.Threading.ManualResetEvent(true);
And also in the top of the form1 added two flags:
bool pause;
bool resume;
Both of the flags are set to false in the constructor.
Then i have a function that is recursive loop:
private List<string> test(string url, int levels,DoWorkEventArgs eve)
{
if (pause == true)
{
_busy.Reset();
}
if (resume == true)
{
_busy.Set();
}
this.Invoke(new MethodInvoker(delegate { label3.Text = label3.Text = (Int32.Parse(label12.Text) + Int32.Parse(label10.Text)).ToString(); }));
HtmlWeb hw = new HtmlWeb();
List<string> webSites;
List<string> csFiles = new List<string>();
csFiles.Add("temp string to know that something is happening in level = " + levels.ToString());
csFiles.Add("current site name in this level is : " + url);
try
{
this.Invoke(new MethodInvoker(delegate { ColorText.Texts(richTextBox1, "Loading The Url: " , Color.Red); }));
this.Invoke(new MethodInvoker(delegate { ColorText.Texts(richTextBox1, url + "...",Color.Blue); }));
HtmlAgilityPack.HtmlDocument doc = TimeOut.getHtmlDocumentWebClient(url, false, "", 0, "", "");
this.Invoke(new MethodInvoker(delegate { ColorText.Texts(richTextBox1, " Done " + Environment.NewLine, Color.Red); }));
currentCrawlingSite.Add(url);
webSites = getLinks(doc);
removeDupes(webSites);
removeDuplicates(webSites, currentCrawlingSite);
removeDuplicates(webSites, sitesToCrawl);
if (removeExt == true)
{
for (int i = 0; i < webSites.Count; i++)
{
webSites.Remove(removeExternals(webSites));
}
}
if (downLoadImages == true)
{
webContent.retrieveImages(url); }
if (levels > 0)
sitesToCrawl.AddRange(webSites
this.Invoke(new MethodInvoker(delegate { label7.Text = sitesToCrawl.Count.ToString(); }));
this.Invoke(new MethodInvoker(delegate { label12.Text = currentCrawlingSite.Count.ToString(); }));
if (levels == 0)
{
return csFiles;
}
else
{
for (int i = 0; i < webSites.Count(); i++)//&& i < 20; i++) {
string t = webSites[i];
if ((t.StartsWith("http://") == true) || (t.StartsWith("https://") == true)) // replace this with future FilterJunkLinks function
{
csFiles.AddRange(test(t, levels - 1, eve));
}
}
return csFiles;
}
}
catch
{
failedUrls++;
this.Invoke(new MethodInvoker(delegate { label10.Text = failedUrls.ToString(); }));
this.Invoke(new MethodInvoker(delegate { ColorText.Texts(richTextBox1, " Failed " + Environment.NewLine, Color.Green); }));
return csFiles;
}
}
In the backgroundworker DoWork event i added this:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
_busy.WaitOne();
this.Invoke(new MethodInvoker(delegate { label2.Text = "Website To Crawl: "; }));
this.Invoke(new MethodInvoker(delegate { label4.Text = mainUrl; }));
test(mainUrl, levelsToCrawl, e);
}
Then i have two buttons click events one for pause one for resume:
private void button4_Click(object sender, EventArgs e)
{
pause = true;
}
private void button5_Click(object sender, EventArgs e)
{
resume = true;
}
But when i click on the button pause nothing happens either on the resume button. The process is keep going on. I tried also without flags just in each button to make _busy.Reset(); and _busy.Set(); but nothing.
What i want is to pause somehow the recursive loop and to resume it. Im not sure if its connected to the backgroundworker or not but the idea is to pause and resume the process.
What should i do ?
Thanks.
_busy.WaitOne();
That's the statement that would cause the worker to pause. However, it only appears at the start of DoWork(), where the event will never be reset yet. You'll need to move it inside the loop.
The second bug, one you haven't run into yet, is that once you paused you can never resume again. Because the worker is not running anymore and won't be paying attention to the resume variable. Get rid of those variables, your Click event should directly call the Set() and Reset() methods.
I am writing a c# program to let me know when a file has been added or deleted. I run it on my Windows 7 machine and watch an FTP server on our network.
It works fine but will suddenly stop catching any events. I'm guessing that it might be losing connection to the server or there is a glitch in the network.
How can I handle this situation in the code. Is there some exception I can watch for and try to restart the FileSystemWatcher object.
Any suggestions and code samples would be appreciated.
I needed to add an error handler for the FileSystemWatcher
fileSystemWatcher.Error += new ErrorEventHandler(OnError);
And then add this code:
private void OnError(object source, ErrorEventArgs e)
{
if (e.GetException().GetType() == typeof(InternalBufferOverflowException))
{
txtResults.Text += "Error: File System Watcher internal buffer overflow at " + DateTime.Now + "\r\n";
}
else
{
txtResults.Text += "Error: Watched directory not accessible at " + DateTime.Now + "\r\n";
}
NotAccessibleError(fileSystemWatcher ,e);
}
Here is how I reset the SystemFileWatcher object:
static void NotAccessibleError(FileSystemWatcher source, ErrorEventArgs e)
{
source.EnableRaisingEvents = false;
int iMaxAttempts = 120;
int iTimeOut = 30000;
int i = 0;
while (source.EnableRaisingEvents == false && i < iMaxAttempts)
{
i += 1;
try
{
source.EnableRaisingEvents = true;
}
catch
{
source.EnableRaisingEvents = false;
System.Threading.Thread.Sleep(iTimeOut);
}
}
}
I think this code should do what I want it to do.
The previous answer does not fix it completely, I had to reset the watcher not just turn it on and off.
I use filesystemwatcher on a window service
void NotAccessibleError(FileSystemWatcher source, ErrorEventArgs e)
{
int iMaxAttempts = 120;
int iTimeOut = 30000;
int i = 0;
while ((!Directory.Exists(source.Path) || source.EnableRaisingEvents == false) && i < iMaxAttempts)
{
i += 1;
try
{
source.EnableRaisingEvents = false;
if (!Directory.Exists(source.Path))
{
MyEventLog.WriteEntry("Directory Inaccessible " + source.Path + " at " + DateTime.Now.ToString("HH:mm:ss"));
System.Threading.Thread.Sleep(iTimeOut);
}
else
{
// ReInitialize the Component
source.Dispose();
source = null;
source = new System.IO.FileSystemWatcher();
((System.ComponentModel.ISupportInitialize)(source)).BeginInit();
source.EnableRaisingEvents = true;
source.Filter = "*.tif";
source.Path = #"\\server\dir";
source.NotifyFilter = System.IO.NotifyFilters.FileName;
source.Created += new System.IO.FileSystemEventHandler(fswCatchImages_Changed);
source.Renamed += new System.IO.RenamedEventHandler(fswCatchImages_Renamed);
source.Error += new ErrorEventHandler(OnError);
((System.ComponentModel.ISupportInitialize)(source)).EndInit();
MyEventLog.WriteEntry("Try to Restart RaisingEvents Watcher at " + DateTime.Now.ToString("HH:mm:ss"));
}
}
catch (Exception error)
{
MyEventLog.WriteEntry("Error trying Restart Service " + error.StackTrace + " at " + DateTime.Now.ToString("HH:mm:ss"));
source.EnableRaisingEvents = false;
System.Threading.Thread.Sleep(iTimeOut);
}
}
}
You can create a method that initiates the FileSystemWatcher, and in case of an error, just restart it.
private void WatchFile()
{
try
{
fsw = new FileSystemWatcher(path, filter)
{
EnableRaisingEvents = true
};
fsw.Changed += Fsw_Changed;
fsw.Error += Fsw_Error;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
private void Fsw_Error(object sender, ErrorEventArgs e)
{
Thread.Sleep(1000);
fsw.Changed -= Fsw_Changed;
fsw.Error -= Fsw_Error;
WatchFile();
}
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.