How can I turn this code snippet into a blocking function?

  • Thread starter Thread starter Jamie Risk
  • Start date Start date
J

Jamie Risk

How can I rewrite 'getSpecialData()' more so that it more elegantly waits
for the handler to complete?

- Jamie

class someClass {
private class SpecialData { ... }
private SpecialData specialData;
private bool blocking;

private void retrievedHandler(SpecialData d)
{ specialData = d; blocking = false; }

public SpecialData getSpecialData()
{
Retriever rtvr = new Retriever(new
DataRetrievedHandler(retrievedHandler));
blocking = true;
rtvr.fetch();
while(blocking) {}
return this.specialData;
}
}
 
Jamie Risk said:
How can I rewrite 'getSpecialData()' more so that it more elegantly waits
for the handler to complete?

- Jamie

class someClass
{
private class SpecialData { ... }
private SpecialData specialData;

private ManualResetEvent m_event = new ManualResetEvent( false );

private void retrievedHandler(SpecialData d)
{
specialData = d;
m_event.Set();
}

public SpecialData getSpecialData()
{
Retriever rtvr = new Retriever(
new DataRetrievedHandler(retrievedHandler));

m_event.Reset();
rtvr.fetch();
m_event.WaitOne();

return this.specialData;
}
}
 
Hello Jamie,
How can I rewrite 'getSpecialData()' more so that it more elegantly
waits for the handler to complete?

- Jamie

class someClass {
private class SpecialData { ... }
private SpecialData specialData;
private bool blocking;
private void retrievedHandler(SpecialData d)
{ specialData = d; blocking = false; }
public SpecialData getSpecialData()
{
Retriever rtvr = new Retriever(new
DataRetrievedHandler(retrievedHandler));
blocking = true;
rtvr.fetch();
while(blocking) {}
return this.specialData;
}
}

Just wondering... Why? If you're offloading processing to another thread,
why block the one you're currently in... It doesn't make sense to me. Why
not just retrieve the data synchronously. It would be much easier and in
the end you'll get the same result.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top