无法创建可靠的“监视文件夹"在 UWP 应用中 [英] Can't Create Reliable "Watch Folder" in UWP App

查看:19
本文介绍了无法创建可靠的“监视文件夹"在 UWP 应用中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class WatchFolder
{
    public bool ChangesMade { get; set; }

    public WatchFolder()
    {
        ChangesMade = false;
    }

    public async void InitializeFolderWatch()
    {
        var folder = KnownFolders.PicturesLibrary.GetFolderAsync("TestWatchFolder");
        var options = new QueryOptions();
        options.FolderDepth = FolderDepth.Deep;
        var fileQuery = folder.CreateFileQueryWithOptions(options);
        fileQuery.ContentsChanged += OnContentsChangedFolder;
        var files = await fileQuery.GetFilesAsync();           
    }

    private void OnContentsChangedFolder(IStorageQueryResultBase sender, object args)
    {
        ChangesMade = true;
    }
}

我正在尝试让监视文件夹适用于 Windows 10 应用商店应用.调试时,上面的代码起初工作正常.每次我使用 Windows 文件资源管理器将文件添加到监视文件夹(或删除一个)时,该事件都会触发并将继续触发.但是,如果我与 应用程序的 UI 交互几秒钟,然后再试一次,此后不会触发.

I'm trying to get a watch folder working for a Windows 10 Store app. When debugging the above code works fine at first. The event fires and will continue to fire every time I add a file to the watch folder (or remove one) using Windows File Explorer. But if I interact with the uwp app's UI for a few seconds then then try again it won't fire thereafter.

我尝试在代码隐藏和视图模型中实例化它,结果相同.我也尝试将其转换为静态方法,结果相同.

I have tried instantiating it in both the code-behind and the view model, same result. I've also tried converting it to a static method, same result.

推荐答案

这是因为 fileQuery 对象超出范围,当您与 UWP 应用交互时,GC 正在启动并从内存中删除对象.

It is because the fileQuery object is going out of scope and when you are interacting with the UWP app, the GC is kicking in and removing the object from memory.

尝试使 fileQuery 对象成为类中的私有字段,这样它就不会超出范围,直到您不再需要该类.

try to make the fileQuery object a private field in the class, this way it wont go out of scope until you don't need the class anymore.

这篇关于无法创建可靠的“监视文件夹"在 UWP 应用中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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