Ehs*_*udi 2 c# asynchronous async-await
我只是写下面的代码,我希望在C#中有3个带异步功能的文本文件,但我没有看到任何内容:
private async void Form1_Load(object sender, EventArgs e)
{
Task<int> file1 = test();
Task<int> file2 = test();
Task<int> file3 = test();
int output1 = await file1;
int output2 = await file2;
int output3 = await file3;
}
async Task<int> test()
{
return await Task.Run(() =>
{
string content = "";
for (int i = 0; i < 100000; i++)
{
content += i.ToString();
}
System.IO.File.WriteAllText(string.Format(@"c:\test\{0}.txt", new Random().Next(1, 5000)), content);
return 1;
});
}
Run Code Online (Sandbox Code Playgroud)
有一些潜在的问题:
c:\test\存在?如果没有,你会收到一个错误.Random对象可能生成相同的数字,因为当前系统时间用作种子,并且您几乎在同一时间执行这些操作.您可以通过让它们共享static Random实例来解决此问题.编辑:但您需要以某种方式同步对它的访问.我选择了一个简单lock的Random实例,这不是最快的,但适用于这个例子.string这种方式构建很长效率非常低(例如,对于我来说,在调试模式下大约需要43秒,要做一次).你的任务可能正常工作,你没有注意到它实际上正在做任何事情,因为它需要很长时间才能完成.使用StringBuilder该类可以使速度更快(例如约20毫秒).async和写的await关键字test().它们是多余的,因为Task.Run已经返回了Task<int>.这对我有用:
private async void Form1_Load(object sender, EventArgs e)
{
Task<int> file1 = test();
Task<int> file2 = test();
Task<int> file3 = test();
int output1 = await file1;
int output2 = await file2;
int output3 = await file3;
}
static Random r = new Random();
Task<int> test()
{
return Task.Run(() =>
{
var content = new StringBuilder();
for (int i = 0; i < 100000; i++)
{
content.Append(i);
}
int n;
lock (r) n = r.Next(1, 5000);
System.IO.File.WriteAllText(string.Format(@"c:\test\{0}.txt", n), content.ToString());
return 1;
});
}
Run Code Online (Sandbox Code Playgroud)