小编Rao*_*bin的帖子

静态变量的线程安全初始化

我一直在使用这种模式来初始化我的类中的静态数据.它看起来对我来说是安全的,但我知道细微的线程问题是多么微妙.这是代码:

public class MyClass // bad code, do not use
{
    static string _myResource = "";
    static volatile bool _init = false;
    public MyClass()
    {
        if (_init == true) return;
        lock (_myResource)
        {
            if (_init == true) return;
            Thread.Sleep(3000); // some operation that takes a long time 
            _myResource = "Hello World";
            _init = true;
        }
    }
    public string MyResource { get { return _myResource; } }
}
Run Code Online (Sandbox Code Playgroud)

这里有洞吗?也许有一种更简单的方法可以做到这一点.

更新:共识似乎是静态构造函数是要走的路.我使用静态构造函数提出了以下版本.

public class MyClass
{
    static MyClass() // a static constructor
    { …
Run Code Online (Sandbox Code Playgroud)

c# singleton multithreading

15
推荐指数
2
解决办法
8723
查看次数

数据绑定到WPF中的UserControl

我有一个UserControl,我想参与数据绑定.我在用户控件中设置了依赖项属性,但无法使其工作.

当我用静态文本(例如BlueText ="ABC")调用它时,uc显示正确的文本.当我尝试将它绑定到本地公共属性时,它始终是空白的.

<src:BlueTextBox BlueText="Feeling blue" />            <!--OK-->
<src:BlueTextBox BlueText="{Binding Path=MyString}" /> <!--UserControl always BLANK!-->
<TextBox Text="{Binding Path=MyString}" Width="100"/>  <!--Simple TextBox Binds OK-->
Run Code Online (Sandbox Code Playgroud)

我已将代码简化为以下简化示例.这是UserControl的XAML:

    <UserControl x:Class="Binding2.BlueTextBox" ...
    <Grid>
        <TextBox x:Name="myTextBox" Text="{Binding BlueText}" Foreground="Blue" Width="100" Height="26" />
    </Grid>
Run Code Online (Sandbox Code Playgroud)

以下是UserControl背后的代码:

public partial class BlueTextBox : UserControl
{
    public BlueTextBox()
    {
        InitializeComponent(); 
        DataContext = this; // shouldn't do this - see solution
    }

    public static readonly DependencyProperty BlueTextProperty =
        DependencyProperty.Register("BlueText", typeof(string), typeof(BlueTextBox));

    public string BlueText
    {
        get { return GetValue(BlueTextProperty).ToString(); }
        set { …
Run Code Online (Sandbox Code Playgroud)

c# wpf xaml wpf-controls

11
推荐指数
1
解决办法
1万
查看次数

标签 统计

c# ×2

multithreading ×1

singleton ×1

wpf ×1

wpf-controls ×1

xaml ×1