Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#wait运算符只能在异步方法中使用,但该方法是异步的_C#_Windows_Asynchronous - Fatal编程技术网

C#wait运算符只能在异步方法中使用,但该方法是异步的

C#wait运算符只能在异步方法中使用,但该方法是异步的,c#,windows,asynchronous,C#,Windows,Asynchronous,第行错误:wait instance.CreateFile();wait运算符只能在异步方法中使用。考虑使用Assic修饰符标记此方法并将其返回类型改为任务 据我所知,该方法已经是异步的,我不确定我做错了什么。这是VS 2015中的UWP应用程序 public sealed partial class MainPage : Page { private List<Customer> Customers; public MainPage() {

第行错误:wait instance.CreateFile();wait运算符只能在异步方法中使用。考虑使用Assic修饰符标记此方法并将其返回类型改为任务 据我所知,该方法已经是异步的,我不确定我做错了什么。这是VS 2015中的UWP应用程序

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;

    }
 }
公共密封部分类主页面:第页
{
私人名单客户;
公共主页()
{
this.InitializeComponent();
CustomerDataAccessLayer实例=新建CustomerDataAccessLayer();
等待instance.CreateFile();
}
}
公共类CustomerDataAccessLayer
{
公共存储文件;
公共异步任务CreateFile()
{
mfile=wait ApplicationData.Current.LocalFolder.GetFileAsync(“Customers.xml”);
if(mfile==null)
{
mfile=wait ApplicationData.Current.LocalFolder.CreateFileAsync(“Customers.xml”,CreationCollisionOption.ReplaceExisting);
}
其他的
{
}
返回;
}
}

正如其他人所指出的,错误消息抱怨调用方法不是
async
,但构造函数不能标记为
async


核心问题是UI不能异步加载-它必须立即加载。我建议首先加载某种“加载…”状态,并启动异步操作。然后,当该操作完成时,更新UI以显示数据。

要从同步函数(如构造函数)启动异步操作,可以使用任务

Task.Run(async () =>
{
    //put your async code here
});
要等待此任务,您必须使用更多的代码

Task t = new Task(() => { /*Your code*/ });
t.Wait();

这是一个构造函数,不,它没有标记为
async
(也不能)。您可以从它的声明中缺少
async
关键字看出。但是它没有async,所以它不是..?您不能在构造函数中使用async/await。
async
不遵循方法链,每个使用
wait
的单独函数都必须标记为
async
,但是正如@Servy所说,您不能将构造函数标记为
async
。所以方法不能标记为async?我在public async Task CreateFile()中确实有关键字,我是否必须将其更改为类?方法和构造函数之间存在差异。构造函数不是普通的方法(它们没有显式的返回类型,它是隐含的),并且不能用
async
修饰它们。方法可以用它来修饰,基本上你的问题归结为在构造函数中使用
await
,这是不允许的。不要使用
await
,而是使用
instance.CreateFile.Wait()
(no
await
),它允许您调用异步方法,而无需同步等待(将阻塞)。