Reputation: 387
I am learning/ experimenting with the Async Await features. I have a button click event that calls this code:
//first select the direcgtory in this event. Then called the async function..to be written
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
foldername = folderBrowserDialog1.SelectedPath;
}
// CreateFilesParellel();
var x = CreateAsync();
Here is what the function CreateAsync looks like: Mode details go here
async Task<int> CreateAsync()
{
string fileType;
List<Task> tasks = new List<Task>();
//get the files in the existing directory.
var files = Directory.GetFiles(foldername);
fileType = Path.GetExtension(files[0]);
var filepath = Path.GetFullPath(files[0]);
string d = Path.GetDirectoryName(files[0]);
var ss = Path.GetFileNameWithoutExtension(files[0]);
var progress = new Progress<string>();
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 100000; i++)
{
Action act = () =>
{
File.Copy(files[0], d + "\\" + ss + i.ToString() + fileType);
};
//await File.Copy(files[0], d + "\\" + ss + i.ToString() + fileType);
Task t = new Task(act);
tasks.Add(t);
// t.Start();
progress.ProgressChanged += (s, e) =>
{
textBox1.Text = System.Environment.NewLine;
textBox1.Text = "Creating file = " + e;
};
}
await Task.WhenAll(tasks);
sw.Stop();
string ExecutionTimeTaken = string.Format("Minutes :{0}\nSeconds :{1}\n Mili seconds :{2}", sw.Elapsed.Minutes, sw.Elapsed.Seconds, sw.Elapsed.TotalMilliseconds);
MessageBox.Show(ExecutionTimeTaken);
return 0;
}
So here is the question. When I run this code nothing happens. Meaning files are not getting created. What am I doing wrong? Or what am I missing?
Upvotes: 1
Views: 331
Reputation: 564891
You never start your Task
.
In general, you should use Task.Run
, not new Task
, to create (already running) tasks.
// Replace:
// Task t = new Task(act);
// tasks.Add(t);
// With:
tasks.Add(Task.Run(act));
That being said, this is likely not a good candidate for this type of parallelism (creating multiple tasks). Since you're doing pure disk IO, you'll likely receive a bottleneck on the drive itself.
You'd likely be better off leaving this routine as a non-async, serial routine, and just wrapping it in a single Task.Run
at your call site:
//first select the direcgtory in this event. Then called the async function..to be written
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
foldername = folderBrowserDialog1.SelectedPath;
}
int result = await Task.Run(CreateFiles);
Upvotes: 6