I am new to C# and WinForms.I programmed a Progressbar that reads text from file and displays that text above the bar.That updating process happens on a separate thread, it updates it every 2s.It works but sometimes when I close the programm I get an error something like:accesing disposed object. The error occurs at the code I provided under this text specifically at Invoke(new MethodInvoker(()=>{UpdateMsgText(msgText);}));
private void UpdateMsgText(string msgText)
{
if(InvokeRequired){
Invoke(new MethodInvoker(()=>{UpdateMsgText(msgText);}));
}
else
{
processingInfo.Text=msgText;
}
This is where the function is being called:
private async void BackgroundWorker()
{
if (string.IsNullOrEmpty(m_Arguments.m_ProgressFilePath))
{
MessageBox.Show(GetValueFromResourceFile("WarningProgressPathNotProvided"));
CloseForm();
}
while (IsFinsihed() == false && IsDisposed == false)
{
string progressText = ReadTextFromFile(m_Arguments.m_ProgressFilePath);
string msgText = ReadTextFromFile(m_Arguments.m_MsgFilePath);
int progress = 0;
if (!string.IsNullOrEmpty(progressText))
{
TryUpdateSingleValue(progressText, ref progress);
}
if (!string.IsNullOrEmpty(msgText))
{
//if the text is to big to fit in progressViewer the UI will not display that text
if (!IsMessageTooLong(msgText))
{
UpdateMsgText(msgText);
m_MessageBoxTooLongTextShown = false;
}
}
if (progress >= 100)
{
CloseForm();
break;
}
if (progress < 0)
{
UpdateProgressBar(0);
}
await Task.Delay(m_Arguments.m_ThreadDelayTime);
}
}
I tried using if (InvokeRequired &&!isDisposed)
and also try catch block but nothing worked.