I have a method like this:
public IOrganizationService GetConnection(bool multi)
{
if(!multi)
{
Parallel.For(0, 1, i =>
{
dynamic _serviceobject= InitializeCRMService();
});
}
else
{
ThreadPool.QueueUserWorkItem
(
new WaitCallback
(
(_) =>
{
dynamic _serviceobject= InitializeCRMService();
}
)
);
}
}
I want to return the _serviceobject *directly* from inside the method.Will returing it twice i.e once from if and once from the else loop solve my problem.Please note I am using Multithreading using the concept of Pool threading.Will the _serviceobjects stay unique in case two threads are running parallely.I do not wan’t any interaction to happen between my threads.
The code inside of
WaitCallbackwill execute in the thread pool, and will do so probably afterGetConnectionhas returned (that’s the point of doing asynchronous operations). So, since it is another thread (with another call stack) and it will potentially execute afterGetConnectionhas returned, you cannot makeGetConnectionreturn from inside ofWaitCallback. If you really want to do that, then you will have to makeGetConnectionwait untilWaitCallbackhas completed execution. ManualResetEvent can do the trick:But doing this defies the point of having asynchronous operations in the first place. Since the caller thread will have to wait until the job is done in another thread, sitting there, doing nothing… Then, why don’t just do it synchrnously? In a word: Pointless.
The problems is that returning the value directly is a synchronous API. If you want asyncrhonous operations, you will want an asycrhonous API. If you will have an asynchronous API then you are going to have to change the way the caller works.
Solutions include:
Notes:
Personally I would go for the callback option:
The caller then does something like this: