【问题标题】:Async method doesnt continue to following code异步方法不会继续跟随代码
【发布时间】:2015-08-24 16:20:33
【问题描述】:

我想为我发送的对象创建一些嵌套文件夹,如果我在等待之后调试它时有父 ID,它的行为就像打破它没有遵循下一个代码行我能做什么我在互联网上找不到任何解决方案。

public class FileOperations
{
    StorageFolder newFile,newFolder;
    List<StorageFolder> folderList = new List<StorageFolder>();
    public async void CreatingFiles(int cat, int par, string name)
    {
        StorageFolder folder = Windows.Storage.ApplicationData.Current.LocalFolder;
        if (par == 0)
        {
            StorageFolder file = Windows.Storage.ApplicationData.Current.LocalFolder;
            newFile = await file.CreateFolderAsync(name, CreationCollisionOption.ReplaceExisting);
            folderList.Add(newFile);
        }

        else
        {
            for (int i = 1; i <= folderList.Count; i++)
                if (par == i)
                {
                    newFolder =  await folderList[par - 1].CreateFolderAsync(name, CreationCollisionOption.ReplaceExisting);
folderList.Add(newFolder);
                }
        }
    }
    public Task InitializeAsync()
    {
        return InitializeOfflineFilesAsync();
    }

    private Task InitializeOfflineFilesAsync()
    {
        throw new NotImplementedException();
    }

    private async Task<StorageFolder> CF(string name, CreationCollisionOption replaceExisting, StorageFolder file)
    {
        return await file.CreateFolderAsync(name, replaceExisting);
    }
}

【问题讨论】:

  • 有什么问题?什么不起作用?另外,您的 else 部分对循环有什么作用?它让我想起了For-If-Antipattern
  • 你还应该避免使用async void 方法。它们几乎只存在于事件处理程序中。 async Task 是异步等价于 void 同步方法。
  • 你怎么称呼这个?您的调用堆栈是否有WaitResult

标签: c# asynchronous async-await


【解决方案1】:

您是否尝试过为“CreatingFiles”方法返回 Task 类型而不是 void 并使用 await 调用“CreatingFiles”方法?

例如等待创建文件(...);

我猜你多次调用 async 方法,你不希望其他 async 方法在前一个 async 方法完成之前启动,但它确实如此。为防止出现这种情况,您必须使用 await 调用“CreatingFiles”方法,等待其完成后再继续执行。

希望对你有帮助。

【讨论】:

    【解决方案2】:

    异步是指不依赖于彼此结果的进程,因此可以同时发生在不同的线程上。所以我认为问题是你跑了三分之一,然后你打开不同的三分之一,如果你想继续,你必须在同一个三分之一。解决方案是在中断的行代码上使用dispecher:

    App.Current.Dispatcher.Invoke(async () =>
    {
        var x = await ...;
    });
    

    【讨论】:

    • 它在调度程序上不起作用它说“'Application'不包含'Dispatcher'的定义,并且找不到接受'Application'类型的第一个参数的扩展方法'Dispatcher'(您是否缺少 using 指令或程序集引用?)”它不接受 using System.Windows.Threading
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-07
    • 1970-01-01
    • 2022-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多