等待似乎悄然回归

时间:2013-02-28 02:48:37

标签: c# windows-store-apps

我有一个方法在异步方法上调用await。

private async void LoadPic(string imageFileName)
{
    StorageFolder sf = Windows.ApplicationModel.Package.Current.InstalledLocation;
    StorageFolder subFolder = await sf.GetFolderAsync("Assets");
    StorageFile sfile = await subFolder.GetFileAsync(imageFileName);

当我在下一行设置断点时,断点永远不会被击中。它只是退出方法并返回。

public PixelData GrabPixelData(string imageFileName)
{
    if (!ImageDictionary.ContainsKey(imageFileName))
    {
        // doesn't exist yet, so load it
        LoadPic(imageFileName);
    }

    PixelData pd = new PixelData();
    bool found = false;
    while( found == false ) {
        found = ImageDictionary.TryGetValue(imageFileName, out pd);
    }
    return pd;
   // throw new NullReferenceException();
}

在我调用LoadPic()后,我添加了一个循环,不断检查是否将此文件中的图像添加到Dictionary中。它似乎永远不会被添加而只是挂起。

这个方法适用于我从中抽象出来的子类。


编辑:

修改了几件事。现在一切似乎都有效,但是当我将结果分配给子类时,我得到一个空的异常错误(即使调试器没有指示任何东西是空的!)。

我想知道它是否与任务包装有关。

儿童班:

private async void LoadPic()
{
     // I realize the async void is to be avoided, but ... I'm not sure because there isn't anything I want it to return. Should it just return a dummy task?
     sat1.pixelData = await rootPage.GrabPixelData("sat1.png");

LoadPic:

        private async Task<PixelData> LoadPic(string imageFileName)
        {
            StorageFolder sf = Windows.ApplicationModel.Package.Current.InstalledLocation;
            StorageFolder subFolder = await sf.GetFolderAsync("Assets");
            StorageFile sfile = await subFolder.GetFileAsync(imageFileName);
...
            return pd;

GrabPixelData:

public async Task<PixelData> GrabPixelData(string imageFileName)
{
    if (!ImageDictionary.ContainsKey(imageFileName))
    {
        // doesn't exist yet, so load it
        PixelData pd = await LoadPic(imageFileName);
        ImageDictionary.Add(imageFileName, pd);
    }

    var test = ImageDictionary[imageFileName];

    return ImageDictionary[imageFileName];
}

1 个答案:

答案 0 :(得分:4)

你应该避免async void。此外,轮询共享状态以检测异步操作的完成是禁忌。这种CPU使用率可能会使您的应用程序从Windows应用商店中被拒绝。

我建议您更改LoadPic以返回Task<PixelData>。然后将ImageDictionaryDictionary<string, PixelData>更改为Dictionary<string, Task<PixelData>>。您的GrabPixelData方法可能如下所示:

public Task<PixelData> GrabPixelData(string imageFileName)
{
  if (!ImageDictionary.ContainsKey(imageFileName))
  {
    // doesn't exist yet, so load it
    ImageDictionary.Add(imageFileName, LoadPic(imageFileName));
  }

  return ImageDictionary[imageFileName];
}