I am attempting to learn about async programming by following the blog article here. I am running into a compiler error that states I must use a lambda expression with await. The answer is provided here, and here, but I am not grasping how to incorporate the solution into the example from MSDN that I am attempting to work with.
The following error is thrown with this line:
int processed = await UploadAndProcessAsync(image);
The 'await' operator can only be used within an async lambda expression. Consider marking this lambda expression with the 'async' modifier.
From this code:
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.
}
}
}