简体   繁体   English

处置传递给线程的对象的正确方法是什么?

[英]What is the correct way to dispose an object passed to a thread?

Given the following piece of code: 给出以下代码:

ThreadWork thrdwrk = new ThreadWork();

Thread t = new Thread(() => thrdwrk.do_work(inc_client));
t.Start();      

What is the correct procedure, or best practice, to make sure that the thrdwrk disposal method is called? 确保调用thrdwrk处理方法的正确程序或最佳实践是什么? thrdwrk implements iDisposable. thrdwrk实现iDisposable。

If any objects contained within thrdwrk were not thread safe - would this prevent it or cause issues? 如果thrdwrk中包含的任何对象thrdwrk是线程安全的,这会阻止它或引起问题吗?

I've not been able to find any documentation that calls out specifically what the process is in this scenario. 在这种情况下,我找不到任何专门说明该过程的文档。

In order to prevent issues with premature disposing, the rule of thumb is that disposable objects should be disposed by whoever created them. 为了防止过早处置问题,经验法则是,凡是创建一次性物品的人,都应该对其进行处置。 It's counterintuitive to split the responsibility of creating/disposing of an object to two different actors. 将创建/处置对象的责任分配给两个不同的参与者是违反直觉的。

Forgetting the threading for a second , the general idea would be to do: 一秒钟忘了线程 ,通常的想法是:

ThreadWork thrdwrk = new ThreadWork();

doSomeThings(thrdwrk);

thrdwrk.Dispose();

A using pattern would be better here: 在这里using模式会更好:

using(ThreadWork thrdwrk = new ThreadWork())
{
    doSomeThings(thrdwrk);
}

However, the threaded nature of your particular case makes it hard to gauge when the object can actually be disposed of. 但是,特殊情况下的螺纹性质使得很难确定何时可以真正处置该物体。 This is a more nuanced consideration based on the surrouding context, which is not clear from your question. 基于环绕的上下文,这是一个更加细致的考虑,您的问题尚不清楚。

Ideally, you adhere to the rule of thumb. 理想情况下,您坚持经验法则。 Wait until the thread has finished , then you know you can safely dispose of the object. 等待直到线程完成 ,然后您就可以安全地处置该对象了。

Alternatively, if you're convinced that the object should be disposed of by the thread and don't want to implement logic to wait for the thread's completion, then you should be consistent and have the thread create its own disposable object as well. 另外,如果您确信该对象应该由线程处理,并且不想实现逻辑来等待线程完成,那么您应该保持一致,并让线程也创建自己的一次性对象。
I see no benefit to creating an object in a scope where its only purpose is to pass it to a lower scope. 我认为在仅将对象传递给较低范围的范围内创建对象没有任何好处。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM