Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multithreading best practicies

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?

like image 466
Jack Malkovich Avatar asked Apr 22 '26 03:04

Jack Malkovich


1 Answers

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.

like image 122
Marc Gravell Avatar answered Apr 23 '26 15:04

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!