gpt4 book ai didi

c# - 遵循异步进度和取消的 MSDN 博客示例时出现 Lamba 错误

转载 作者:太空宇宙 更新时间:2023-11-03 10:28:07 24 4
gpt4 key购买 nike

我正尝试通过阅读博客文章 here 来了解异步编程.我遇到了一个编译器错误,指出我必须将 lambda 表达式与 await 一起使用。提供了答案here , 和 here ,但我没有掌握如何将解决方案合并到我尝试使用的 MSDN 示例中。

此行抛出以下错误:

int processed = await UploadAndProcessAsync(image);

'await' 运算符只能在异步 lambda 表达式中使用。考虑使用“async”修饰符标记此 lambda 表达式。

来自这段代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Windows.Forms;

namespace AsyncAttempt
{
public partial class Form1 : Form
{

public Form1()
{
InitializeComponent();
}

async Task<int> UploadPicturesAsync(List<Image> imageList, IProgress<int> progress)
{
int totalCount = imageList.Count;
int processCount = await Task.Run<int>(() =>
{
int tempCount = 0;
foreach (var image in imageList)
{
//await the processing and uploading logic here
int processed = await UploadAndProcessAsync(image);
if (progress != null)
{
progress.Report((tempCount * 100 / totalCount));
}
tempCount++;
}

return tempCount;
});
return processCount;
}

private Task<int> UploadAndProcessAsync(Image image)
{
throw new NotImplementedException();
}

private async void Start_Button_Click(object sender, RoutedEventArgs e)
{
//construct Progress<T>, passing ReportProgress as the Action<T>
var progressIndicator = new Progress<int>(ReportProgress);
//call async method
int uploads = await UploadPicturesAsync(GenerateTestImages(), progressIndicator);
}

private List<Image> GenerateTestImages()
{
throw new NotImplementedException();
}

void ReportProgress(int value)
{
//Update the UI to reflect the progress value that is passed back.
}

}
}

最佳答案

这个:

int processCount = await Task.Run<int>(() => /* process image */)

将使用 lambda 表达式创建委托(delegate)。为了让您能够在其中await,需要将其标记为async:

int processCount = await Task.Run<int>(async () => /* process image */)

关于c# - 遵循异步进度和取消的 MSDN 博客示例时出现 Lamba 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31084767/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com