Reputation: 806
I'm writing dll, which does some things asyncronously. some operations with databse for instance. example:
(new Action(()=>
{
// database blablabla
}
)).BeginInvoke((x)=>{}
,null);
i know, about threadqueue, about backgroundworkers, about Thread class and etc. my question: what is the best way to do it? am i doing it right? can it cause any troubles in future?
Upvotes: 3
Views: 99
Reputation: 456507
I have an article on my blog that discusses the relative merits of several approaches to asynchronous/background tasks. Asynchronous delegates are quite low-level.
I recommend you use a Task
-based approach. Not only does this have the best support for aspects like error handling and return values, but it also sets you up for future success when the async CTP becomes mainstream. If you have time, read through the Task-Based Asynchronous Pattern document - it describes some things still being developed, but has excellent instructions for how to design a Task
-based API.
Also keep in mind Marc's warnings about the database connection and thread safety. You can use task schedulers from the parallel extensions samples to properly access the db connection while keeping a Task
-based API.
Upvotes: 0
Reputation: 1062780
If you use a delegate's BeginInvoke
, you are responsible for ensuring that EndInvoke
gets called. I suspect that ThreadPool
(or a custom work-queue / worker-thread(s)) would be a better idea.
Another thing to watch out for is the calling context; you will no longer have access to anything about the request, so any information (for example, the site if doing multi-tenancy) must be captured in advance.
Careful thread safety is obviously a concern, but impossible to give specific warnings about without a specific example.
Finally; be careful about the DB connection; connections aren't thread-safe, so you might want to ensure you have an isolated connection inside your worker, as you have no way of predicting what any connection in the calling context is doing; it could be disposed, or could be busy doing something. Don't use it.
Upvotes: 1