gpt4 book ai didi

c# - 异步等待...和任务。我究竟做错了什么

转载 作者:太空宇宙 更新时间:2023-11-03 19:14:18 25 4
gpt4 key购买 nike

我正在学习/试验异步等待功能。我有一个调用此代码的按钮单击事件:

       //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();

这是函数 CreateAsync 的样子:模式详细信息在此处

    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;


}

那么问题来了。当我运行这段代码时,什么也没有发生。意思是文件没有被创建。我究竟做错了什么?或者我错过了什么?

最佳答案

您永远不会开始您的任务

一般来说,您应该使用Task.Run,而不是new Task,来创建(已经运行的)任务。

// Replace:
// Task t = new Task(act);
// tasks.Add(t);

// With:
tasks.Add(Task.Run(act));

也就是说,这可能不是这种并行性(创建多个任务)的理想选择。由于您正在执行纯磁盘 IO,因此您可能会遇到驱动器本身的瓶颈。

您可能最好将此例程保留为非异步串行例程,并将其包装在调用站点的单个 Task.Run 中:

   //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);

关于c# - 异步等待...和任务。我究竟做错了什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18257194/

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