Hey all,
I'm trying to write a program with a couple background workers in it. In the background worker DoWork() function I have a few EventLog calls that call a delegate to another function with a textwriter inside. I'm using the background worker reportprogress for something else so I would really like to know what is wrong with my code below? I get errors that another thread is using the textwriter.
public delegate void EventLogCallback(string newEvent);
public partial class Main : Form
{
EventLogCallback EventLog;
public Main()
{
InitializeComponent();
EventLog = new EventLogCallback(AddEventLog);
}
private void Main_Load(object sender, EventArgs e)
{
bwDatabase.RunWorkerAsync();
for (int i = 0; i < 1000; i++)
{
if (i % 2 == 1)
EventLog("Main: " + i.ToString()); //odd
else
EventLog("Main: " + i.ToString()); //even
}
}
private void AddEventLog(string eventMsg)
{
string filename = @"c:\Log\Log for " + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Day.ToString() + "-" + DateTime.Now.Year.ToString() + ".txt";
if (eventMsg != sLastEvent)
{
sLastEvent = eventMsg;
eventMsg = DateTime.Now.ToString() + ": " + eventMsg;
system.EventList.Add(eventMsg);
TextWriter wText = new StreamWriter(filename,true);
wText.WriteLine(eventMsg);
wText.Close();
}
}
private void bwDatabase_DoWork(object sender, DoWorkEventArgs e)
{
EventLog.Invoke("Database Thread Started");
for (int i = 0; i < 1000; i++)
{
if (i % 2 == 1)
EventLog("SQL: " + i.ToString()); //odd
else
EventLog.Invoke("SQL: " + i.ToString()); //even
}
As you can see, I tried EventLog directly and EventLog.invoke to no avail. What am I doing wrong?
Thanks,
Jeremy