我正在尝试在 GUI 系统中的两个线程之间同步。系统的主要任务是初始化两个同步对象并运行两个线程:private FetcherAPI fetcherAPI { get; set; }private FileReader fileReader { get; set; }private object readerLocker;private object writerLocker;public Form1() { InitializeComponent(); this.fetcherAPI = new FetcherAPI(); this.fileReader = new FileReader(); readerLocker = new object(); writerLocker = new object(); new Thread(() => { this.fileReader.run(readerLocker); }); new Thread(() => { this.fixerAPI.run(writerLocker, readerLocker); });}private void button1_Click(object sender, EventArgs e) { Monitor.Pulse(writerLocker);}读者主题:public void run(object readerLocker) { while(true) { Monitor.Wait(readerLocker); readDataFromFileAndPresent(); }}作者主题:public void run(object writerLocker, object readerLocker) { while(true) { Monitor.Wait(writerLocker); fetchCurrency(); Monitor.Pulse(readerLocker); Monitor.Wait(readerLocker); }}当按下按钮时,我收到以下错误:object synchronization method was called from an unsynchronized block of code我究竟做错了什么?
1 回答
慕姐8265434
TA贡献1813条经验 获得超2个赞
仅当您已经拥有锁时(即您位于语句内,或者您已成功用于获取锁),Wait
才Pulse
可以调用两者。你还没有做过这两件事,所以:确实,它不会起作用。最简单的修复方法是添加一个.lock
Monitor.Enter
lock(writerLocker)
- 1 回答
- 0 关注
- 86 浏览
添加回答
举报
0/150
提交
取消