I'm converting my old - legacy - web application that process - parse - uploaded files. It uses pure javascript + MVC.
/* javascript */
function Parse(files) {
var idFiles=document.getElementById('inputF').value;
CallServer('ProcessFile/Parse', idFiles, function (m)
{
if (m != null)
{
var om = JSON.parse(m);
MsgLog('Parse finished ' + om.msg);
}
});
}
var CallServer = function (url, content, callback) {
var rqs = new XMLHttpRequest();
rqs.open('POST', url, true);
rqs.onreadystatechange = function () {
if (rqs.readyState == 4 && rqs.status == 200) {
callback(rqs.responseText);
return true;
} else { return false; }
};
rqs.send(content);
}
/* View */
...
<a href="#" id="parseFiles" onclick="Parse()" title="Parse selected documents">Parse</a>
...
/* Controller */
public JsonResult Parse(string idFiles){
// parses input string and returns an array of int
int[] idf=getIds(idFiles);
string wholeFile=string.Empty;
string parsedData=string.Empty;
string outputFileName=string.Empty;
List<string> doneFiles=new List<string>();
foreach(int f in idf)
{
wholeFile=ReadFile(f);
parsedData=ParseFile(wholeFile);
outputFileName=SaveParsed(parsedData);
doneFiles.Add(outputFileName);
}
return Json(new { doneFiles });
}
The controller returns data to view showing the list of parsed files. Since parsing takes long to run, I'm trying to convert this code into a async/await Task + Parallel (?) code. I rewrote the Parse method but I'm a bit confused on async/await Task + Parallel stuffs. Moreover I don't know if I have to change javascript. Now the controller looks like:
public JsonResult Parse(string idFiles){
int[] idf=getIds(idFiles);
string wholeFile=string.Empty;
string parsedData=string.Empty;
string outputFileName=string.Empty;
List<string> doneFiles=new List<string>();
await Task.Run(() =>Parallel.ForEach(idf, async currFile =>
{
wholeFile=ReadFile(currFile);
Task<string> parseData=ParseFile(wholeFile);
await Task.WhenAll(parseData);
Task<string> write = await parseData.ContinueWith(async (aa) => await SaveParsed(parsedData));
Task.WhenAll(write);
}
return Json(new { doneFiles });
}
My desiderata would be a true async Parse method that when finished update the list of parsed files in the view... file1 - parsed file2 - parsed file3 -