C#.NET WPF中的基本线程锁定 [英] Basic Thread Locking in C#.NET WPF

查看:80
本文介绍了C#.NET WPF中的基本线程锁定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎是一个基本问题,但是Google并没有帮助我...如何在C#.NET WPF中进行基本线程锁定?在我相当简单的用户应用程序中,我有多个线程执行耗时的操作,这些操作将其结果保存到一个通用数据结构中或从该通用数据结构中读取.我希望能够在访问此数据结构的周围进行lock()和unlock()维护线程安全.但是,在我的代码中有很多不同的地方,我可以从其中访问这个数据结构,而不仅仅是一个.哪些.NET对象用于实现此锁定?

解决方案

尝试一下:

public static class LockHolder
{
    public static object Lock = new object();
}

然后在您的代码中使用:

lock(LockHolder.Lock)
{
    //your safe code
}

http://msdn.microsoft.com /en-us/library/c5kehkcz(v=vs.71).aspx

我想更多信息可能会有所帮助. IIRC,lock(object o)本质上是一个宏,它将由编译器扩展,然后限制对您期望的安全代码的访问.不一定很明显,任何对象o可以是一个锁,并且每个o对于每个安全锁都是必需的.如果我有

object a = new object();
object b = new object();

并执行lock(a),则不会阻止访问带有lock(b)的内容.大多数代码示例都显示一个lock(this),它将锁定到特定类的当前实例,如果您需要全局锁定并具有该类的多个实例,则这不是您想要的. /p>

This seems like a basic question, but Google has not helped me... How do I do basic thread locking in C#.NET WPF? In my fairly simple user application, I have multiple threads performing time-intensive operations that save their results into one common data structure or read from this common data structure. I'd like to be able to lock() and unlock() around access to this data structure to maintain thread safety. However, there are many different places in my code that I access this data structure from, not just one. What .NET objects are used to implement this locking?

解决方案

try this:

public static class LockHolder
{
    public static object Lock = new object();
}

then, in your code, use:

lock(LockHolder.Lock)
{
    //your safe code
}

http://msdn.microsoft.com/en-us/library/c5kehkcz(v=vs.71).aspx

I guess a little more info may be helpful. IIRC, the lock(object o) is basicly a macro that will be expanded by the compiler and then restrict access to your safe code, which is what you'd expect. What isn't necessarily obvious is that any object o can be a lock, and each o is needed for each safe lock. if I have

object a = new object();
object b = new object();

and perform a lock(a) then that will not prevent access to something with a lock(b) around it. Most code samples show a lock(this) which will lock to the current instance of the particular class, which is not what you want if you need a global lock and have multiple instances of that class running around.

这篇关于C#.NET WPF中的基本线程锁定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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