views:

83

answers:

1

I have a C# application using a C++ DLL. The C++ DLL is extremely simple. I can call one method, and it has a callback method. The callback method must finish before I can process the next item.

The problem is, I can only process one command at a time, but I want to process them as fast as possible.

Fake/simplified code interface for c++ DLL:

void AddNumbers(int a, int b, AddNumbersCallback callback);

Now lets try to use it:

void DoStuff()
{
     if(MyCollection.HasStuff)
          AddNumbers(MyCollection.First().a, MyCollection.First.b, StuffDone);
}

void StuffDone(int result)
{
    //I wish I could process the next item here, but the callback isn't done!
    //DoStuff();
}

The root of the problem is that I want to execute code after the callback is done.

My temporary solution was to queue an item in the threadpool, and wait 100ms. Typically, that will give the method time to "finish".

And "no", I can't change the DLL.

+1  A: 

If the function is truly asynchronous, then it shouldn't matter how many times you call it, or how long you wait between calls. (Read: your DLL is broken.) In a case like that, if you really need synchronization, you'll probably want to use an EventWaitHandle in a loop.

using System.Threading;

EventWaitHandle done = new EventWaitHandle(false, EventResetMode.AutoReset);

void DoStuff()
{
    while (MyCollection.HasStuff)
    {
        // note: something smelled fishy here.
        // i assume your collection removes the first entry when you call First
        var first = MyCollection.First();
        AddNumbers(first.a, first.b, StuffDone);
        done.WaitOne();
    }
}

void StuffDone(int result)
{
    done.Set();
}
cHao
But does that guarantee that the "done.WaitOne();" line will not let execution continue until "StuffDone" has completed?The problem, it seems, is that "StuffDone" must be off the call stack before I can process the next item.
Jason Young
You can't really guarantee something like that without knowing the thread handles of both threads beforehand, which no DLL worth its money would rely on you coding around. I'm thinking perhaps the DLL isn't really asynchronous (it's just calling the callback when it's done), and with a lot of entries, the call to DoStuff() from the callback would overflow the stack. The EventWaitHandle stuff should account for that case, as well as for when things are truly async and you're waiting on whatever processing you're doing in StuffDone.
cHao