What I have is something similar to this:
//method being called by thread pool thread
public string someFunction(){
string someString = "string";
//Stuff happens
//Need to wait for 5 seconds without blocking thread
return someString;
}
The issue is that I need the result of that method returned to the method that called it, however, I do not want it returned immediately and I do not want to block the thread. Is there a way that I can make the thread pause at that line for a specified amount of time and release the thread back into the thread pool, and then after some timeout, one of the thread pool threads picks up where it left off and completes the function and returns?
All… After spending some time with your responses, I realize now that doing what I am trying to achieve is not so much possible in the context in which I want it.
A little explanation though. I am trying to create a rudimentary long poll web server in c sharp for a web based chat application I am building. I was wanting to have the thread enter a method where it waits until one of two things happens, either data shows up for the client, or a poll timeout occurs. However, I did not want the thread to block, I have some time in the past implemented something where each client got a thread and the thread blocked and trust me… it is NOT a good idea. The 5 seconds in the example was arbitrary and the actual time will likely sit somewhere between 1 and 5 minutes. In the end, the structure I may end up going with is a sort of client management thread. a thread that works its way through a list asking each client if the client has work to be done. If the client has reached its timeout or has data waiting in its queue, then the appropriate method gets dispatched into the thread pool and and the Client Management thread continues on to the next client.
Something like so…
while(true){
foreach(Client client in ClientList){
//check if the client has something it needs done
if(client.needsWork){
//invoke the appropriate method asynchronously
delegate = client.appropriateInvokable;
delegate.beginInvoke();
}
}
}
Thank you all considerably for your help and patience!
After looking through your question, I see it’s a bit trickier than just getting a timer callback on a new thread. The real issue is that your call is structured to return a value synchronously, so there is no way you can avoid blocking the calling thread. The correct way to avoid blocking is to change your call to use an asynchronous callback rather than returning the value directly. If you have access to the TPL, one nice way to do this is to return a Task object that the caller can then Wait on immediately or register for a callback.
That said, for the timing callback aspect, I have some utility code that I use to simplify working with System.Threading.Timer in these one-off timer scenarios. I’ve cut it down to the specified functionality and put it below: