2

I'm trying to sync between two threads in my GUI system.

The main task of the system initialising two synchronisation objects and running two threads:

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);
}

Reader Thread:

public void run(object readerLocker) {
    while(true) {
        Monitor.Wait(readerLocker);
        readDataFromFileAndPresent();
    }
}

Writer Thread:

public void run(object writerLocker, object readerLocker) {
    while(true) {
        Monitor.Wait(writerLocker);
        fetchCurrency();
        Monitor.Pulse(readerLocker);
        Monitor.Wait(readerLocker);   
    }
}

When pressing the button I'm getting the following error:

object synchronization method was called from an unsynchronized block of code

What am I doing wrong?

Yinon
  • 945
  • 1
  • 8
  • 21
  • it seems to me that the pulse and wait calls have to be inside a `lock` statement – Mong Zhu Aug 27 '19 at 16:45
  • either [this answer](https://stackoverflow.com/a/20386028/5174469) or [this one](https://stackoverflow.com/a/3797900/5174469) or even [this one](https://stackoverflow.com/a/3798033/5174469) should answer your question – Mong Zhu Aug 27 '19 at 16:48

1 Answers1

2

Both Wait and Pulse can only be called if you already have the lock, i.e. you're inside a lock statement, or you've successfully used Monitor.Enter to acquire the lock. You haven't done either of those things, so : indeed, it won't work. The simplest fix would be to add a lock(writerLocker).

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900