I'm writing an email module and Im having lots of strange errors with
threads.
The form has a similar look to outlook express.
I've several buttons that I use to switch between Inbox/Sent/Draft/Deleted
items for displaying in the list.
Thread 1 checks for new incoming mail every minute and adds new messages to
the list when necessary.
Thread 2 looks at the selected item in the list and sets button
enabled/disabled etc
Thread 3 is fired when the selected item in the list changes and changes
it's message status to Read after 1sec
There's an OnSelectedItemChange event that fires when the selected item
changes in the list to display the mail in a preview window.
I get problems when I click one of the buttons to change between
Inbox/Sent/Draft/Deleted then follow that quickly with selecting an item in
the list. It falls over on quantifying lstMail.SelectedItem and it's as if
the list is being built while thread 2 fires off.
SelectedItem "System.IndexOutOfRangeException"
I'm calling the thread methods using Invoke on the form so I don't really
understand why this is happening and I didnt have the problem when I did the
same thing using a Timer object rather than thread. Can someone tell me
where I'm going wrong please.
// Thread 2 loop
private void StatusThreadMethod()
{
string fnName = "StatusThreadMethod";
while(true)
{
try
{
Thread.Sleep(500);
Invoke(new EmptyEventDelegate(StatusThreadInvokeMethod));
}
catch(Exception e)
{
LogException(fnName, e);
Invoke(new OnThreadExceptionDelegate(OnThreadException), new object[]
{e});
}// catch
}// while
}// function
private void StatusThreadInvokeMethod()
{
string fnName = "StatusThreadInvokeMethod";
try
{
// Update form buttons enabled/disabled
UpdateButtons();
}
catch(Exception e)
{
LogException(fnName, e);
throw e;
}
}// function
private void UpdateButtons()
{
string fnName = "UpdateButtons";
try
{
MessageCentreMessage message = null;
// Following line is where it falls over with exception above <<<<<<<<
if (lstMail.SelectedItem != null)message =
(MessageCentreMessage)lstMail.SelectedItem;
btnRestore.Enabled = ((message != null)&&(lstMail.Tag ==
_deletedFolder));
btnReply.Enabled = ((message != null)&&(message.IsMessageIn));
btnForward.Enabled = ((message != null)&&(lstMail.Tag != _draftFolder));
btnDelete.Enabled = (message != null);
btnStandardMessage.Enabled = (lstMail.Tag != null);
btnNew.Enabled = true;
}
catch(Exception e)
{
LogException(fnName, e);
}
}// function