开发者

How can I run a piece of code in the main thread from a different thread?

I am using the class HttpListener as a web server. This server runs on a different thread. At some point this server needs to run some code but it needs to be executed on the main thread. Is there an easy way of doing that?

Thanks!开发者_开发技巧


The bigger question is:

Why do you need to run it on the parent thread? Is it UI Code modifying the UI? Do you need to be within that thread's context to gaurantee thread saftey?

It might be worth stepping back and re-evaluating your threading model, you may be trying to do things in the wrong place.

I Suggest you read This Excelent Free E-Book on C# Threading and learn about the alternate ways of inter-thread communication and look into the Dispatcher if you're using WPF, as it will help delegate events back to the UI Thread if that's what your intent is.

Quick & Dirty Solution Not really the best way

There's any number of ways to approach this, the simplest would probably to have a list of delegates to execute on the main thread. Each time your main thread spins, you lock the collection (unless you're using the multi-threaded collections) and copy out the delegates & clear the collection and release the lock.

Then you simply run them on the main thread.

The problem you'll run into is if you're using blocking on the main thread, your spin cycle will not pass across your delegates till your blocking stops. So if you're say, blocking while you wait for connections, your code will not run till a new person connects.

You could put the server's listen port on it's own thread to solve this.


To do something on the main thread, you will possibly want to inject it via Invoke(), or in the main loop will have some queue of things to do that will be injected from the 'other' threads, in this case HttpListener.

Your example seems similar to mine, where I have 300 threads handling stream ripping, and they are all 'calling' main thread by putting the string messages into the queue for it. It works like a charm. However, when I did try (I dared, just to see what will happen) to Invoke() from at least 30-ish threads to the main message loop, it was weird, to say the least.

Best: use simple Queue< something >, and enqueue it from the other thread, then dequeue it from the UI thread.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜