简体   繁体   English

WPF 中加载文件的异步等待任务错误

[英]Async await task error for load files in WPF

I am trying to do an async operation in UploadBtnExecute method.I am working this on wpf.我正在尝试在UploadBtnExecute方法中执行异步操作。我正在 wpf 上进行此操作。 But it shows some error.但它显示了一些错误。

error are:- error 1::-'错误是:- 错误 1::-'

Task UploadBtnExecute(object)' has the wrong return type任务 UploadBtnExecute(object)' 的返回类型错误

error 2::- '错误 2::- '

bool' does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting a first argument of type 'bool' could be found (are you missing a using directive or an assembly reference?) bool'不包含'GetAwaiter'的定义,并且找不到接受'bool'类型的第一个参数的可访问扩展方法'GetAwaiter'(您是否缺少 using 指令或程序集引用?)

What I have tried:我试过的:

button click event to trigger a function按钮点击事件触发 function

UploadBtnClick = new RelayCommands(UploadBtnExecute,UploadBtnCanExecuteUpload);

public async Task UploadBtnExecute(object param)
{
    Progress windowShow = new Progress();
    windowShow.Show();
    await UploadFiles();
    windowShow.Hide();
}

public bool UploadFiles(List<Item> selectedFiles)
{
    //do some upload code here
    return true;
}

Error 1:错误一:

An event handler must return void .事件处理程序必须返回void This is this case where using async void instead of using async Task is recommended (mainly because there is no alternative, actually) for an async function that doesn't return a value.在这种情况下,对于不返回值的异步 function,建议使用async void而不是async Task (主要是因为实际上没有替代方案)。

Error 2:错误2:

Your second UploadFiles must return a Task<bool> instead of bool for await to make any sense.您的第二个UploadFiles必须返回一个Task<bool>而不是boolawait意义。

Additionally, since this is the function actually doing something asynchronous, you probably wait it to be async Task<bool> and use await on the actual code that uploads something, but that may depend on your actual goal.此外,由于这是实际执行异步操作的 function,您可能会等待它成为async Task<bool>并在上传内容的实际代码上使用await ,但这可能取决于您的实际目标。

So as a summary, your snippet of code should be adapted like that:总而言之,您的代码片段应该像这样调整:

UploadBtnClick = new RelayCommands(UploadBtnExecute,UploadBtnCanExecuteUpload);

public async void UploadBtnExecute(object param)
{
    Progress windowShow = new Progress();
    windowShow.Show();
    await UploadFiles();
    windowShow.Hide();
}

public async Task<bool> UploadFiles(List<Item> selectedFiles)
{
    // do some upload code here
    // using await ....
    return true;
}

// alternatively:
public Task<bool> UploadFiles(List<Item> selectedFiles)
{
    // do some upload code here
    return Task.FromResult(true);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM