提问人:Mark Zhou 提问时间:11/10/2023 更新时间:11/10/2023 访问量:18
C 语言中的 Asyn 方法#
Asyn method in C#
问:
下面的代码示例来自 microsoft .net SDK,
private async void Button_Click(object sender, RoutedEventArgs e)
{
// async keyword here declare this event handler is asynchronous mode.
string StartDirectory = @"c:\Users\exampleuser\start";
string EndDirectory = @"c:\Users\exampleuser\end";
foreach (string filename in Directory.EnumerateFiles(StartDirectory))
{
using (FileStream SourceStream = File.Open(filename, FileMode.Open))
{
using (FileStream DestinationStream = File.Create(EndDirectory +
filename.Substring(filename.LastIndexOf('\\'))))
{
await SourceStream.CopyToAsync(DestinationStream);
}
}
}
}
在这里,每个 await 都会将每个副本的控制权返回给调用方,当
单拷贝开始,单拷贝完成后再回来,这样当需要复制的文件较多时,调用方不会卡住,
我说得对吗?
做一些更改,如下所示
private void Button_Click(object sender, RoutedEventArgs e)
{
//Remove the async, make the event handler become sync.
string StartDirectory = @"c:\Users\exampleuser\start";
string EndDirectory = @"c:\Users\exampleuser\end";
foreach (string filename in Directory.EnumerateFiles(StartDirectory))
{
using (FileStream SourceStream = File.Open(filename, FileMode.Open))
{
using (FileStream DestinationStream = File.Create(EndDirectory +
filename.Substring(filename.LastIndexOf('\\'))))
{
SourceStream.CopyToAsync(DestinationStream);
}
}
}
}
删除 await,但保留 asyn 副本。 我在修改后检查了一下,这会起作用,但我不确定复制行为, 它仍然是异步模式还是成为同步模式?请指教。
答: 暂无答案
评论