0

I'm working on integrating a single-threaded API that does not have any multi-threaded support into a multi-threaded program. I would like to keep all APIinteraction on the main thread and do other stuff on other threads. However the program I am working with has a Producer-Consumer oriented threading design(which I can't modify).

Is there a way I can make threads switch to main thread when I want? Or some other way to get it working?

I apologize for not being able to express the problem clearer

Brent
  • 1,378
  • 2
  • 16
  • 30
  • 4
    What kind of application is this? WinForms, WPF, ASP.NET, Silverlight, Windows Phone 7, Zune, XBox 360, Windows 8 Metro, ...? – Darin Dimitrov Sep 19 '11 at 21:16
  • IT's an fairly low level adaptor between a program API and another program. The top layer is WPF – Brent Sep 20 '11 at 12:53

2 Answers2

1

You can use Control.Invoke on a worker thread to have it run some code on the main user interface thread.

Or maybe you could just synchronize all access to the single-threaded API using lock?

More details would be great, but those are some ideas to get you started.

EDIT: After reading your comment, the easiest & most light-weight way to do it would be to synchronize using lock, as previously mentioned. That way, only one thread calls the 3rd-party API at a time. Example:

static object APILock = new object(); // global variable

// Do this anytime you need to make calls on this non-thread-safe API:
lock (APILock) {
    // call the API; only one thread will run code inside the lock at a time
}

This is generally the accepted way of calling non-thread-safe code.

James Johnston
  • 9,264
  • 9
  • 48
  • 76
  • so the lock stuff didn't work, but the Control.Invoke worked great – Brent Sep 22 '11 at 13:57
  • in my actual code project Control.Invoke does not work, see this [question](http://stackoverflow.com/questions/7517608/control-invoke-does-not-exist-in-the-current-context) – Brent Sep 22 '11 at 16:50
0

You can try to use window messages that are (usually) handled by one "main" thread. Create a window, expose wrappers that mimic your API methods to clients, and send window messages internally. When you handle window messages, call your actual implementation.

That is how COM single-thread apartment model works, and it solves exactly the same problem. However, that is quite advanced solution.

Can't your code be refactored in order to make it thread-safe? That would be simpler, I think.

Sergey Sirotkin
  • 1,668
  • 11
  • 7