Reputation: 19933
In an ASP.NET MVC, when the application start, I need to some connections (LDAP, …) in background. Is there a way to do this “thread safe” in a ASP.NET MVC application ?
Thanks,
Upvotes: 1
Views: 1382
Reputation: 1039588
You should avoid running background tasks in AS.NET. But if for some reason you need to do it, you could start a new thread in Application_Start
and perform those tasks. Since Application_Start
executes only once, this thread will run once (unless of course you configure some timer -> which you probably should not be doing).
If on the other hand you need to consume the work done in this background thread from your ASP.NET MVC controllers (which run inside the context of an HTTP request) you will need proper synchronization in order to ensure that the initialization thread you started in Application_Start
has finished. Depending on your exact scenario there might be different ways to achieve that.
Upvotes: 2
Reputation: 8852
here is a sample how you need to do it, basically we are creating an anonymous delegate
which will Invoke
the function that initiates the connections.
if(this.InvokeRequired)
{
Invoke(new MethodInvoker( () => yourFunctionThatCreatesSomeConnections(Args)));
}
else
{
yourFunctionThatCreatesSomeConnections(Args);
}
Upvotes: 0