C#阻止从其他线程访问所有对象方法 [英] C# prevent access to all object methods from other threads

查看:216
本文介绍了C#阻止从其他线程访问所有对象方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象,一次只能由一个线程使用. 例如,我的对象包含3个方法ABC,并且如果线程访问方法A,我想锁定对象(所有方法/属性均被锁定).

I have an object that have to be used by only a single Thread at a time. For example my Object contains 3 methods A, B and C and I want to lock the object (all the methods/attributes are locked) if a Thread access the method A.

主要困难在于我无法修改该对象的代码.我必须防止在调用对象的地方进行多线程访问.

The main difficultie is that I can't modify the code of that object. I have to prevent multithreads access where i'm calling the object.

我的第一个想法是使用单例模式,但是我没有设法使其正常工作!

My first thought was to use the singleton pattern but i didn't manage to make it work!

推荐答案

如果无法更改对象的代码,则必须处理对象外部的锁定.例如,您可以将其封装在另一个类中(也许将其隐藏在接口后面),并让该包装器类应用同步:

If you can't change the code of the object, you'll have to handle the locking outside the object. For example, you could encapsulate it in another class (maybe hiding it behind an interface), and have that wrapper class apply the synchronization:

public class Foo {
    private readonly YourType tail;
    private readonly object syncLock = new object();
    public Foo(YourType tail) {this.tail = tail;}

    public A() { lock(syncLock) { tail.A(); } }
    public B() { lock(syncLock) { tail.B(); } }
    public C() { lock(syncLock) { tail.C(); } }
}

这篇关于C#阻止从其他线程访问所有对象方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆