Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从集合访问器更新数据库:引发私有事件?_C#_Wpf_Database_Multithreading_Accessor - Fatal编程技术网

C# 从集合访问器更新数据库:引发私有事件?

C# 从集合访问器更新数据库:引发私有事件?,c#,wpf,database,multithreading,accessor,C#,Wpf,Database,Multithreading,Accessor,我需要在类属性更改时更新SQLite数据库。下面是一个糟糕的实现,它确切地说明了需要在更大范围内完成的工作: internal class MyClass { private bool isFoo; internal bool IsFoo { get { return isFoo; } private set { isFoo = value; UpdateDatabase(

我需要在类属性更改时更新SQLite数据库。下面是一个糟糕的实现,它确切地说明了需要在更大范围内完成的工作:

internal class MyClass
{
    private bool isFoo;

    internal bool IsFoo
    {
        get { return isFoo; }

        private set
        {
            isFoo = value;
            UpdateDatabase(); // ← This method could take some time.
        }
    }

    private void UpdateDatabase()
    {
        DatabaseClass.Update(this);
    }
}
用户LukeH在一次采访中说:

如果两个线程同时访问[a属性],则getter将 短暂地阻塞第二个线程,直到它将对象返回到 第一个线程

当前方向

我不想阻止对该物业的访问。如果我实现了
INotifyPropertyChanged
,我的代码要么在保存数据的方式上不一致,要么将
DatabaseClass
变成一堆处理程序。以下是我不愿意使用的方法:

public class MyClass
{
    private bool isFoo;

    internal bool IsFoo
    {
        get { return isFoo; }

        private set
        {
            isFoo = value;
            UpdateRequesting(); // Call delegate, similar to INotifyPropertyChanged
        }
    }

    // Private event and delegate.
    private delegate bool OnUpdateRequesting();
    private event OnUpdateRequesting UpdateRequesting;

    internal MyClass()
    {
        // Subscribe to private event inside of constructor.
        UpdateRequesting += UpdateDatabase;
    }

    // Now, raised by event rather than called directly from set accessor.
    private bool UpdateDatabase()
    {
        return DatabaseClass.Update(this);
    }
}

使用私人活动感觉就像我在拨打自己的电话号码。在不锁定属性的情况下调用
UpdateDatabase()
的正确方法是什么?

只需将
IsAsync=True
添加到
绑定中,第一种方法就可以了。

IsFoo
更改时,您可以从它在UI线程中构建一个Sql命令,然后可以在其他线程中执行。这样,您就可以实现
INotifyPropertyChanged
,而无需problem@Sakura:实现
INotifyPropertyChanged
与上面的代码几乎相同。只需将更新请求的
OnUpdateRequesting
替换为
OnPropertyChanged
;但是,它需要不必要的
MyClass
PropertyChangedEventArgs
实例?您是调用函数来刷新UI,还是为控件设置了值?@Sakura:
get{}set{UpdateRequesting()}
@Sakura:通常,属性是在最终用户单击按钮或更改设置时设置的。