TSM
TSM

Reputation: 582

Non-Blocking Threading

I am re-factoring a C# project that is used by several full-sized applications. This class interacts with hardware and often takes hundreds of milliseconds or more to execute some commands. In many cases, I am replacing Thread.Wait() calls that the previous programmer wrote with ThreadPool calls to perform these actions.

Now, some of the functions this project provides to the several projects using it take hundreds of milliseconds or more to execute and return a value to the calling program that the program must use. My question is whether or not there is some mechanism that I may use within this project to make these calls execute and return on some thread other than the main thread? In other words, I want to make these methods non-blocking from the perspective of this project, rather than require other applications using these functions to place calls in a separate thread.

Thanks

Upvotes: 1

Views: 3044

Answers (4)

NeddySpaghetti
NeddySpaghetti

Reputation: 13495

If you are using .net 4.5 you can use Task.Run to execute the slow operations on a separate thread and then ConfigureAwait(false) to not execute on the main thread once they return.

Task.Run(() => <slow operatoion).ConfigureAwait(false);

Upvotes: 2

nikhil
nikhil

Reputation: 201

i worked on similar stuff ... i would suggest you to use 'select' instead of using threading.... look at this ... if it helps you

http://www.kegel.com/c10k.html

Upvotes: 0

Plymouth223
Plymouth223

Reputation: 1925

Not knowing what version of the framework you're using, have a look at the begin/end async pattern. You should look at changing the API for the project to implement it.

http://msdn.microsoft.com/en-us/library/ms228963.aspx

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564333

In other words, I want to make these methods non-blocking from the perspective of this project, rather than require other applications using these functions to place calls in a separate thread.

In general, the best approach is often to return a Task<T> in this type of scenario. This allows the caller to block if necessary, or use the new await and async keywords to cleanly coordinate with your library, without blocking or forcing them to move to a separate thread.

Upvotes: 5

Related Questions