c# - 后台代理中的静态变量值不同

标签 c# windows-phone

我有一个显示一些数据并启动后台代理以动态更新动态图 block 的应用程序。由于实时磁贴内容是使用从主线程填充的一些变量在后台代理中创建的,我决定(也许这是一个错误的决定,但这是我认为唯一合理的决定)编写一个具有静态变量和属性的类以在主线程之间共享线程和后台代理。 现在的问题是我在主线程中写了一个变量值,但是当后台代理执行时发现这个值是空的。为什么?
我提供了一个小例子,希望它足以让你理解。

静态部分

public class Vars
{
    public static IEnumerable<Contact> Contacts;
    public static void Test()
    {
        int num = Contacts == null ? -2 : Contacts.Count();
        // num is -2 here because Contacts is null !!
    }
}

后台代理

public class TileAgent : ScheduledTaskAgent
{
    protected override void OnInvoke(ScheduledTask task)
    {
        // It's necessary to use BeginInvoke to avoid Cross-thread errors
        Deployment.Current.Dispatcher.BeginInvoke(() =>
        {
            Vars.Test();
        });

        NotifyComplete();
    }
}

主页

public partial class MainPage : PhoneApplicationPage
{
    private void Contacts_SearchCompleted(object sender, ContactsSearchEventArgs e)
    {
        busyIndicator.IsRunning = false;
        try
        {
            Vars.Contacts = e.Results
                .Where(.........);
            ContactResultsData.DataContext = Vars.Contacts;
            // Vars.Contacts.Count() = 67 here !!!

            if (Vars.GetTile() != null)
                StartAgent();
        }
        catch (System.Exception)
        {
            // That's okay, no results
        }
    }
    private void ContactResultsData_Tap(object sender, GestureEventArgs e)
    {
        int num = Vars.Contacts == null ? -2 : Contacts.Count();
        // num = 67 here !!
   }
}

我的代码有什么问题?有没有更好的方法来完成我的任务?
考虑到我在 Windows Phone 上工作不到一个月,所以我确定我仍然在做非常糟糕的事情...

更新:
在放置正确的锁以避免来自不同线程的并发读/写之后,我决定将一个显式静态构造函数放入静态类

public class Vars
{
    static Vars()
    {
        Debug.WriteLine("init");
    }
}

每次调用后台代理时都会调用它!!
这解释了为什么我看到我的变量为空,但我不明白:为什么每次都重新创建一个静态类?
会不会是因为后台代理在一个dll工程里面(需要运行)?
有没有一种方法可以创建一个只在第一次创建的类,可以在不同线程之间共享(它们在这种情况下是进程吗?)?

最佳答案

找了半天,终于找到一个article说明:

Since our EvenTiles application and its PeriodicTask are running in separate processes, they are completely separated from each other, meaning that they get their own copies of variables they both want to access, even though these variables are defined in a separate project.

因此不可能使用“简单的”静态变量/属性在主应用程序和周期性任务之间共享数据;我们必须读/写数据库或隔离存储或任何我们喜欢的东西。

我觉得这很疯狂,但这就是故事。

关于c# - 后台代理中的静态变量值不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11346576/

相关文章:

c# - WP8 KnownContactProperties.Birthdate 无法设置值

c# - 实现逻辑的好方法,在 ListBox (MVVM) 中选择项目时

c# - 打开文件流进行写入 - 强化路径操作

c# - 不点击执行程序

c# - 为什么在为行单元格设置文本时得到 'System.ArgumentOutOfRangeException'?

c# wpf datagrid 添加行

c# - 控制台关闭时不调用终结器

c# - WebBrowser Windows Phone 8 的自动高度

c# - Windows Phone 隔离存储防止文件在退出时损坏

c# - 尝试在音频播放代理中播放音频时出错。 System.SystemException:HRESULT = 0xC00D001A