Reputation: 9
I am trying to execute a simple code. I expect the result RWL works to be shown in the message box. When I press the button, I do wait for events to happen in the textbox.when the text box event occurs, I need to process the result of the event.I am trying to use the read lock mechanism.But its not working.Is there anything wrong in the mechanism?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace ReadWriteLockTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
static ReaderWriterLock rwl = new ReaderWriterLock();
static int resource = 0;
private void button1_Click(object sender, EventArgs e)
{
scanner();
}
private void scanner()
{
int falg = 0;
int i = 0;
while (true)
{
Thread.Sleep(5000);
try
{
rwl.AcquireReaderLock(100);
try
{
Console.WriteLine(i);
i++;
if (resource == 1)
falg = 1;
}
finally
{
rwl.ReleaseReaderLock();
}
}
catch (ApplicationException)
{
}
if (falg == 1)
break;
}
MessageBox.Show("RWL WORKS");
}
private DateTime CharReadTime;
private void textBox1_TextChanged(object sender, EventArgs e)
{
CharReadTime = DateTime.Now;
if (!timer1.Enabled)
timer1.Start();
}
int j = 0;
private void Form1_Load(object sender, EventArgs e)
{
timer1.Enabled = true;
timer1.Interval = 1000;
}
private void timer1_Tick_1(object sender, EventArgs e)
{
const int timeout = 3;
Console.WriteLine("j =" + j);
j++;
if ((DateTime.Now - CharReadTime).Seconds < timeout)
return;
if (String.Compare(textBox1.Text, "") == 0)
return;
try
{
rwl.AcquireWriterLock(100);
try
{
resource = 1;
}
finally
{
rwl.ReleaseWriterLock();
}
}
catch (ApplicationException)
{
}
}
}
}
Upvotes: 0
Views: 440
Reputation: 35869
To add a bit more detail. System.Windows.Forms.Timer (the only Timer class with a Tick event that you have access to in WinForms without adding a WPF assembly) runs the tick event handler on the UI thread. While the scanner method is running, the UI thread is busy and the Tick event handler cannot be invoked. This means that you can never acquire a reader lock at the same time you've acquired a writer lock with the code you've detailed.
Maybe if you detail what you're hoping to accomplish, someone can offer some advice.
Upvotes: 0
Reputation: 3531
The regular timer you drag from the toolbox runs in the UI thread so timer1_tick will never be run at the same time as button1_click. A system.timers.timer runs from another thread and if it's that kind of timer you will need the lock.
I'd suggest using the newer readerwriterlockslim, which is faster and less buggy see https://issues.apache.org/jira/browse/LOG4NET-232 and http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim.aspx
Upvotes: 3