异步方法不会继续遵循代码

时间:2015-08-21 13:37:42

标签: c# asynchronous async-await

我想创建一些嵌套文件夹我发送的对象如果有父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);
    }
}

2 个答案:

答案 0 :(得分:0)

您是否尝试过返回任务类型而不是为&#34; CreatingFiles&#34;方法和调用&#34; CreatingFiles&#34;方法等待?

e.g。等待CreatingFiles(...);

我猜你几次调用异步方法,你不希望在之前的异步方法完成之前启动其他异步方法,但确实如此。要防止出现这种情况,您必须拨打&#34; CreatingFiles&#34;等待等待它继续执行之前完成的方法。

希望它有所帮助。

答案 1 :(得分:-1)

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

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