我正在尝试执行一个简单的代码。我希望结果 RWL 工作将显示在消息框中。当我按下按钮时,我确实等待文本框中发生事件。当文本框事件发生时,我需要处理事件的结果。我正在尝试使用读取锁定机制。但是它不起作用。是机制有什么问题吗?
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)
{
}
}
}
}