c# 调用Monitor.Pulse()时抛出对象同步错误

我正在尝试在 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

我究竟做错了什么?


尚方宝剑之说
浏览 87回答 1
1回答

慕姐8265434

仅当您已经拥有锁时(即您位于语句内,或者您已成功用于获取锁),Wait才Pulse可以调用两者。你还没有做过这两件事,所以:确实,它不会起作用。最简单的修复方法是添加一个.lockMonitor.Enterlock(writerLocker)
打开App,查看更多内容
随时随地看视频慕课网APP