使用String.Empty作为SyncLock对象 [英] Using String.Empty as a SyncLock object

查看:70
本文介绍了使用String.Empty作为SyncLock对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有理由反对编写这样的代码?


class Foo

{

static string _SyncLock = String。空;


public void ThreadSafeMethod()

{

lock(_SyncLock)

{< br $>
//代码到这里

}

}

}

Are there any reasons against writing code like this?

class Foo
{
static string _SyncLock = String.Empty;

public void ThreadSafeMethod()
{
lock (_SyncLock)
{
// Code goes here
}
}
}

推荐答案

3月7日上午7:51,iliti ... @ gmail.com写道:
On Mar 7, 7:51 am, iliti...@gmail.com wrote:

Are有没有理由反对写这样的代码?


class Foo

{

static string _SyncLock = String.Empty;


public void ThreadSafeMethod()

{

lock(_SyncLock)

{

//代码到这里

}

}


}
Are there any reasons against writing code like this?

class Foo
{
static string _SyncLock = String.Empty;

public void ThreadSafeMethod()
{
lock (_SyncLock)
{
// Code goes here
}
}

}



我没有看到任何错误;你锁定了一个实例,

它包含的内容是无关紧要的。一个对象可能有更少的开销

,因为它不需要一个字符数组..

I don''t see anything wrong with it; you''re locking on an instance,
what it contains is irrelevant. An object may have less overhead
though, because it doesn''t need a character array..


3月7日,7:51 am,iliti ... @ gmail.com写道:
On Mar 7, 7:51 am, iliti...@gmail.com wrote:

有没有理由反对编写这样的代码?


class Foo

{

静态字符串_SyncLock = String.Empty;


public void ThreadSafeMethod()

{

锁定(_SyncLock)

{

//代码在这里

}

}


}
Are there any reasons against writing code like this?

class Foo
{
static string _SyncLock = String.Empty;

public void ThreadSafeMethod()
{
lock (_SyncLock)
{
// Code goes here
}
}

}



我唯一关心的是string.Empty可能是一个单身,如果

其他代码决定锁定它,你可能会陷入僵局

条件。可能只是为了锁定一个物体。

My only concern would be that string.Empty may be a singleton, and if
other code decides to lock on it, you could head a deadlock
condition. Might be better just to lock on an object.


3月7日上午6:51,iliti ... @ gmail.com写道:
On Mar 7, 6:51 am, iliti...@gmail.com wrote:

有没有理由反对编写这样的代码?


class Foo

{

静态字符串_SyncLock = String.Empty;


public void ThreadSafeMethod()

{

lock(_SyncLock )

{

//代码来这里

}

}


}
Are there any reasons against writing code like this?

class Foo
{
static string _SyncLock = String.Empty;

public void ThreadSafeMethod()
{
lock (_SyncLock)
{
// Code goes here
}
}

}






我相信String.Empty会返回相同的实例。这意味着如果您在整个应用程序中始终如一地使用此策略

,那么您将拥有完全独立的代码锁定代码。为什么不为此目的实例化

对象?


Brian

Hi,

I''m fairly confident that String.Empty returns the same instance
everytime. That means if you''re using this strategy consistently
throughout your application you''ll have completely independent
sections of code competing for the same lock. Why not instantiate an
Object for this purpose?

Brian


这篇关于使用String.Empty作为SyncLock对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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