我的OnAppearing消息是异步的,因此我调用了另一个异步方法,该方法具有一些修改UI的代码。然后,我做一些工作,最后再次修改UI。
这是代码。但是,我收到的警告消息使我感到困惑。我在下面添加了警告代码。
protected async override void OnAppearing()
{
base.OnAppearing();
// actions
CreateListSectionAsync();
}
public async void CreateListSectionAsync()
{
// modify UI
// do some work that takes time
await Task.Run(() =>
{
Device.BeginInvokeOnMainThread(() =>
{
// modify UI
});
});
}
ListPage.xaml.cs(39,39):警告CS1998:此异步方法缺少 “等待”操作员,将同步运行。考虑使用 'await'操作员等待非阻塞API调用,或'await Task.Run(...)'在后台线程上执行CPU绑定的工作。 (CS1998)
为什么会收到此警告,该如何解决?
答案 0 :(得分:0)
export class UploadComponent {
@ViewChild('file') file: ElementRef;
imagePreview$: Observable<ArrayBuffer | string>;
onFile(event) {
event.preventDefault();
event.stopPropagation();
this.file.nativeElement.click();
}
onImageUpload(event: Event) {
const file = (<HTMLInputElement>event.target).files[0];
this.imagePreview$ = this.fileReaderObs(file);
}
fileReaderObs(blob: Blob): Observable<string> {
return Observable.create(obs => {
if (!(blob instanceof Blob)) {
obs.error(new Error('`blob` must be an instance of File or Blob.'));
return;
}
const reader = new FileReader();
reader.onerror = err => obs.error(err);
reader.onabort = err => obs.error(err);
reader.onload = () => obs.next(reader.result);
reader.onloadend = () => obs.complete();
return reader.readAsDataURL(blob);
});
}
}
<div fxLayout="column">
<div *ngIf="(imagePreview$ | async) as imagePreview">
<img class="img-fluid" [src]="imagePreview" [alt]="" />
</div>
<div fxLayout>
<button fxFlex mat-flat-button color="accent" (click)="onFile($event)">
<mat-icon>cloud_upload</mat-icon>
</button>
<input type="file" #file (change)="onImageUpload($event)" />
</div>
</div>
更改功能的签名以返回不无效的Task
await CreateListSectionAsync();