当前位置: 动力学知识库 > 问答 > 编程问答 >

windows - C# The await operator can only be used within an async method but method is async

问题描述:

Error in line: await instance.CreateFile(); The await operator can only be used within an async method. Consider marking this method with the async modifier and changing its return type to Task

It's my understanding that the method is already asynchronous, I'm not sure what I am doing wrong. This is on a UWP app in VS 2015.

public sealed partial class MainPage : Page

{

private List<Customer> Customers;

public MainPage()

{

this.InitializeComponent();

CustomerDataAccessLayer instance = new CustomerDataAccessLayer();

await instance.CreateFile();

}

}

public class CustomerDataAccessLayer

{

public StorageFile mfile;

public async Task CreateFile()

{

mfile = await ApplicationData.Current.LocalFolder.GetFileAsync("Customers.xml");

if (mfile == null)

{

mfile = await ApplicationData.Current.LocalFolder.CreateFileAsync("Customers.xml", CreationCollisionOption.ReplaceExisting);

}

else

{

}

return;

}

}

网友答案:

As others have noted, the error message is complaining that the calling method is not async, but constructors cannot be marked async.

The core problem is that your UI cannot load asynchronously - it must load immediately. I recommend initially loading some kind of "Loading..." state and also starting an asynchronous operation. Then, when that operation completes, update the UI to display the data.

网友答案:

To start an asynchronous action from a synchronous function (like a constructor), you can use a Task.

Task.Run(async () =>
{
    //put your async code here
});

To await this Task, you have to use some more code.

Task t = new Task(() => { /*Your code*/ });
t.Wait();
分享给朋友:
您可能感兴趣的文章:
随机阅读: