我创建了一个任务循环,结果我应该得到1下载2下载3下载但是我得到1下载1下载1下载也就是说,这些运行任务中的数据没有改变。我想得到结果,就像许多程序一样,在线程中运行,也就是说,一个任务被执行多次并且结果不同
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Leaf.xNet;
using System.Threading;
using System.IO;
namespace Создание_потоков
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private string Random_name()
{
string image = "";
var r = new Random();
while (image.Length < 12)
{
Char c = (char)r.Next(33, 125);
if (Char.IsLetterOrDigit(c))
image += c;
}
return image;
}
void Download_Image()
{
string image_name = Random_name();
HttpRequest request = new HttpRequest();
request.KeepAlive = true;
request.UserAgentRandomize();
var bytes = request.Get("https://thiscatdoesnotexist.com/").ToBytes();
File.WriteAllBytes(image_name + ".jpeg", bytes);
Invoke((MethodInvoker)delegate { textBox1.AppendText(image_name + " Скачалась" + Environment.NewLine); });
}
private async void button1_Click(object sender, EventArgs e)
{
List<Task> tasks = new List<Task>(); // список задач
for (int i = 0; i < 3; i++) // Добавляем циклом задачи, но выполняется как будто один развыполнилась, данные не меняются
{
tasks.Add(Task.Run(() => { Download_Image(); }));
}
await Task.WhenAll(tasks); // ждем всё
}
}
}
你只是对这些任务感到困惑。一切都容易得多。从第三方线程更新文本框内容的唯一方法,我从这里偷了一个方法。