简体   繁体   中英

Threading fiasco problem C#

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM