Need help with multi threading, got error "Cross-thread operation.
- From: Pucca <Pucca@xxxxxxxxxxxxxxxxxxxxxxxxx>
- Date: Mon, 8 Jan 2007 11:35:01 -0800
I'm getting the following error message when I run my applicatino:
Cross-thread operation not valid: Control 'cboFromEvent accessed from a
thread other than the thread it was created on
I step debug the code and it seem to be running through the code "if
(this.cboFromEvent.SelectedIndex == 1)" just fine and I did it for a few
iterations. I then let it run but it happends again witht he same error.
Below is my code can someone see what's wrong here? Thank you.
private void btnRun_Click(object sender, EventArgs e)
{
string header, footer;
Cursor.Current = Cursors.WaitCursor;
//Validate some input
if ((toDate.Value.CompareTo(fromDate.Value)) < 0)
{
MessageBox.Show("The 'To' date can not be less than the
'From' date. Please select a valid date range.");
toDate.Focus();
return;
}
if ((toDate.Value.Date == fromDate.Value.Date) && //if it's the
same day then validate time
(toTime.Value.TimeOfDay < fromTime.Value.TimeOfDay))
{
MessageBox.Show("The 'To' time can not be less than the
'From' time. Please select a valid time range.");
toTime.Focus();
return;
}
int eventCount = lstEvents.Items.Count;
if(eventCount <=0)
{
MessageBox.Show("Please select at least 1 event id for
filtering pupose");
lstEvents.Focus();
return;
}
Cursor.Current = Cursors.WaitCursor;
ReportDocument rdLog = new ReportDocument();
ReportPreview logPreview = new ReportPreview();
dsEventLog dsLog = new dsEventLog();
string eventIDFilter = "", filter = "",eventID, detail,
requestor, groupString = "", sortString = "", reportPath,
account;
int index = 0;
//Get all the filter selection
int counter = lstEvents.SelectedItems.Count;
for (index=0; index < counter; index++)
{
CListItem item = lstEvents.SelectedItems[index] as CListItem;
if (item != null)
{
if (index > 0)
eventIDFilter += ", ";
eventIDFilter += (item.valueItem);
}
}
//Get the Filter string
filter += "Events generated between " +
fromDate.Value.ToShortDateString() +
" " + fromDate.Value.ToLongTimeString() + " and " +
toDate.Value.ToShortDateString() +
toDate.Value.ToShortTimeString() + "; ";
filter += "Event ID = " + eventIDFilter;
if(timeChanged)
filter += "Time from " + fromTime.Value.ToLongTimeString() +
" to " +
toTime.Value.ToLongTimeString() + "; ";
if((reportName.Contains("All")) || (reportName == "Password
Changes Report"))
reportPath = Application.StartupPath + "\\" + "All Logonoff
And All Kerberos.rpt";
else if(reportName.Contains("Kerberos"))
reportPath = Application.StartupPath + "\\" +
"KerberosLog.rpt";
else
reportPath = Application.StartupPath + "\\" + "EventLog.rpt";
rdLog.Load(reportPath);
//Get the grouping and the sorting attributes
DataRow groupRow = dsLog.Tables["Grouping"].NewRow();
DataRow sortRow = dsLog.Tables["Sorting"].NewRow();
//Fill the Group table
for (counter = 0; counter < lsvGroup.Items.Count; counter++)
{
if (counter > 0)
groupString += ",";
groupString += lsvGroup.Items[counter].Text;
groupRow[counter] = lsvGroup.Items[counter].Text;
}
if(lsvGroup.Items.Count > 0)
dsLog.Tables["Grouping"].Rows.Add(groupRow);
//Fill the sort and the order tables
SortFields sortFields = rdLog.DataDefinition.SortFields;
SortField sortField;
index = 0;
for(counter = 0; counter < lsvSort.Items.Count; counter++)
{
//Remove the redundent sort attribute if it is already a
group attribute
if(!groupString.Contains(lsvSort.Items[counter].SubItems[0].ToString()))
{
if (counter > 0)
sortString += ",";
sortString += lsvSort.Items[counter].Text + "-" +
lsvSort.Items[counter].SubItems[1].Text;
sortRow[index] = lsvSort.Items[counter].Text;
sortField = sortFields[index+ 8];
if(lsvSort.Items[counter].SubItems[1].Text ==
"Ascending")
sortField.SortDirection =
SortDirection.AscendingOrder;
else
sortField.SortDirection =
SortDirection.DescendingOrder;
index++;
//rdLog.DataDefinition.SortFields[index].Field =
lsvSort.Items[counter].Text;
}
}
dsLog.Tables["Sorting"].Rows.Add(sortRow);
System.Diagnostics.EventLogEntry padLogEntry;
padLogEntry = padLogEntryCollection[0];
header = txtHeader.Text;
footer = txtFooter.Text;
header = header.Replace("\\n", "\n");
footer = footer.Replace("\\n", "\n");
DataRow globalRow = dsLog.Tables["Global"].NewRow();
globalRow["Footer"] = footer;
globalRow["Filter"] = filter;
globalRow["Heading"] = header;
globalRow["SortBy"] = sortString;
globalRow["GroupBy"] = groupString;
globalRow["Computer"] = padLogEntry.MachineName;
globalRow["UserName"] = Environment.UserName;
dsLog.Tables["Global"].Rows.Add(globalRow);
int oneFortith, barCount = 1;
oneFortith = (int)(logCount / 40);
MethodInvoker newMethodInvoker = delegate
{
try
{
//GetLog();
//Iterate through all 'EventLogEntry' instances in
'EventLog'.
for (int i = logCount - 1; i > 0; i--)
{
if ((oneFortith * barCount) == i)
{
this._progressDialog.Value = barCount;
}
padLogEntry = padLogEntryCollection[i];
detail = padLogEntry.Message;
eventID = padLogEntry.InstanceId.ToString();
//if (eventID == "672")
// MessageBox.Show("got it");
//filter the data
if (reportName.Contains("Successful"))
{
if (padLogEntry.EntryType ==
EventLogEntryType.FailureAudit)
continue;
}
else if (reportName.Contains("Failed"))
{
if (padLogEntry.EntryType ==
EventLogEntryType.SuccessAudit)
continue;
}
if (eventIDFilter.Contains(eventID))
{
if (this.cboFromEvent.SelectedIndex ==
1)//Events On is selected
{
if ((padLogEntry.TimeGenerated.Date <
fromDate.Value.Date) &&
(padLogEntry.TimeGenerated.TimeOfDay <
fromTime.Value.TimeOfDay))
{
continue;
}
}
else if (this.cboToEvent.SelectedIndex ==
1)//Events On is selected
{
if ((padLogEntry.TimeGenerated.Date >
toDate.Value.Date) &&
(padLogEntry.TimeGenerated.TimeOfDay >
toTime.Value.TimeOfDay))
continue;
}
DataRow dr = dsLog.Tables[0].NewRow();
if (padLogEntry.EntryType ==
EventLogEntryType.SuccessAudit)
dr["Type"] = "Success";
else
dr["Type"] = "Failed";
dr["Date"] =
padLogEntry.TimeGenerated.ToShortDateString();
dr["Time"] =
padLogEntry.TimeGenerated.ToLongTimeString();
dr["Event"] = eventID;
index = detail.IndexOf(":");
if (eventID == "681")
dr["Description"] = "Failed logon attempt";
else if (index != -1)
dr["Description"] = detail.Substring(0,
index);
if (reportName.Contains("Kerberos")) //Get the
Client Address
{
dr["ClientAddress"] =
CUnityDS.GetMessageField(detail, "Client Address:", false);
}
else
{
if (eventID == "681")
dr["Requestor"] = padLogEntry.UserName;
else
{
//Get Requestor and the Detail
requestor =
CUnityDS.GetMessageField(detail, "Caller Domain:", false);
requestor += '\\' +
CUnityDS.GetMessageField(detail, "Caller User Name:", false);
if (requestor.Length <= 1)//If blank
then remove the slash
requestor = "";
else
dr["Requestor"] = requestor;
}
}
if (eventID == "680")
dr["Account"] = padLogEntry.UserName;
else
{
account = GetAccount(detail, eventID,
padLogEntry.EntryType);
if (account.Length <= 1)
dr["Account"] = "";
else
dr["Account"] = account;
}
if ((eventID == "627") || (eventID == "628"))
dr["Detail"] = "";
else
dr["Detail"] = GetDetail(detail, eventID);
dsLog.Tables[0].Rows.Add(dr);
this._progressDialog.PerformStep();
}
}//End for loop
this._progressDialog.CloseForm();//Close the progress
window
if (dsLog.Tables["dtEventLog"].Rows.Count <= 0)
{
MessageBox.Show("No record found matches your
selection.", MessageBoxButtons.OK, MessageBoxIcon.Information);
goto CleanUp;
}
rdLog.SetDataSource(dsLog);
logPreview.crViewer.ReportSource = rdLog;
if (dsLog.Tables["Grouping"].Rows.Count <= 0)
{
logPreview.crViewer.ShowGroupTreeButton = false;
logPreview.crViewer.DisplayGroupTree = false;
}
//processingMsg.Refresh();
//logPreview.crViewer.RefreshReport();
}
catch (ThreadAbortException exeption)
{
goto Next;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString(),
MessageBoxButtons.OK, MessageBoxIcon.Error);
goto CleanUp;
}
Next:
DialogResult dResult;
int pages = dsLog.Tables[0].Rows.Count / 20;
if (ckbPreview.Checked == true)
{
if (pages > 1000)//Warn user if this report has more than
1000 pages
{
dResult = MessageBox.Show("There are over " +
Convert.ToString(pages) +
" pages in this report and this could take up to
several minutes to process. Please click the Cancel button if " +
"you would like to narrow down on your selection
filter, or clik the OK button to continue creating the report? ",
MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
if (dResult == DialogResult.OK)
logPreview.ShowDialog();
else
goto CleanUp;
}
else
logPreview.ShowDialog();
}
else
{
logPreview.crViewer.PrintReport();
}
CleanUp:
dsLog.Tables[0].Rows.Clear();
dsLog.Tables[1].Rows.Clear();
dsLog.Tables[2].Rows.Clear();
dsLog.Tables[3].Rows.Clear();
logPreview.Dispose();
rdLog.Dispose();
dsLog.Dispose();
filter = "";
sortString = "";
groupString = "";
//All done, clean up
//dsLog.Tables.Clear();//Remove relation first
GC.Collect();
Cursor = Cursors.Default;
};//end delegates
//System.Diagnostics.Debug.WriteLine("current thread: " +
Thread.CurrentThread.ManagedThreadId);
this._progressDialog = new frmGeneratingReport(logCount,
newMethodInvoker);
this._progressDialog.Step = 1;
this._progressDialog.Maximum = 1000;
this._progressDialog.ShowDialog();
}
--
Thanks.
.
- Follow-Ups:
- Re: Need help with multi threading, got error "Cross-thread operation.
- From: Jon Skeet [C# MVP]
- Re: Need help with multi threading, got error "Cross-thread operation.
- Prev by Date: How to save web page to MHT from ASP.NET / C# application?
- Next by Date: Re: need help on regular expression pattern
- Previous by thread: How to save web page to MHT from ASP.NET / C# application?
- Next by thread: Re: Need help with multi threading, got error "Cross-thread operation.
- Index(es):