首先,请不要评价我,我对编程很陌生。我想做一个PC->安卓应用,把我选择的文件发送到我的手机上。它的工作,一切都很好,除了方法不是异步的。所以,如果我向手机发送东西,我的UI会冻结,直到发送完成。谁能帮帮我?我一直在阅读所有关于异步方法的文档,但我就是搞不懂,我该如何实现它?
下面是一些需要的代码。
这是 "发送 "文件的事件,我希望它是异步的。
private void button2_Click(object sender, EventArgs e) {
await push();
}
public async Task push() {
if (folder != null) {
string ip = textBox1.Text + "." + textBox2.Text + "." + textBox3.Text + "." + textBox4.Text;
listBox1.Items.Add("Creating a test server on the machine on port " + 8001 + ". Host ip: " + ip);
server = new Server(ip, 8001);
listBox1.Items.Add("Server running.");
int i = 0;
listBox1.Items.Add("Fetching files...");
getFileNum(folder, ref i);
listBox1.Items.Add("Files scanned. Current number: " + i + " files.");
//send number of files to be transmitted
listBox1.Items.Add("Getting your files ready... please standby.");
server.send(i.ToString());
listBox1.Items.Add("Your files are ready, beggining the transmitting process.");
//actual method for sending files
sendFiles(folder);
listBox1.Items.Add(".");
listBox1.Items.Add(".");
listBox1.Items.Add("Files sent!");
}
else {
MessageBox.Show("No directory path selected.", "Error_null_path");
}
}
public async Task<Task> sendFiles(DirectoryInfo dir) {
FileInfo[] files = dir.GetFiles();
DirectoryInfo[] dirs = dir.GetDirectories();
string path = dir.FullName + "/";
foreach (FileInfo file in files) {
await server.sendFile(path + file.Name, folder.FullName.Replace(folder.Name,""));
listBox1.Items.Add("Sent file: " + file.Name);
}
foreach (DirectoryInfo subDir in dirs) {
await sendFiles(subDir);
}
return null;
}
这是发送部分的代码,在 "服务器 "类中。
public async Task sendFile(string filePath, string root) {
FileInfo file = new FileInfo(filePath);
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
server.Bind(new IPEndPoint(IPAddress.Parse(ip), port));
//send song name length
server.Listen(0);
Socket client = server.Accept();
byte[] send;
if (filePath.Replace(root, "").Length < 10)
send = new UTF8Encoding(true).GetBytes("0" + filePath.Replace(root, "").Length);
else
send = new UTF8Encoding(true).GetBytes(filePath.Replace(root, "").Length.ToString());
client.Send(send);
client.Close();
server.Close();
//send song name
server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
server.Bind(new IPEndPoint(IPAddress.Parse(ip), port));
server.Listen(0);
client = server.Accept();
send = new UTF8Encoding(true).GetBytes(filePath.Replace(root,""));
client.Send(send);
client.Close();
server.Close();
//send the song
server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
server.Bind(new IPEndPoint(IPAddress.Parse(ip), port));
server.Listen(0);
client = server.Accept();
client.SendFile(file.FullName);
client.Close();
server.Close();
//return null;
}
public async Task send(string data) {
switch (data.Length) {
case 1:
data = "000" + data;
break;
case 2:
data = "00" + data;
break;
case 3:
data = "0" + data;
break;
default:
data = "0000";
break;
}
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
server.Bind(new IPEndPoint(IPAddress.Parse(ip), port));
server.Listen(0);
Socket client = server.Accept();
byte[] send = new UTF8Encoding(true).GetBytes(data);
client.Send(send);
client.Close();
server.Close();
//return null;
}
我是一个很新的编程
提示:注意编译器的警告。它们会指出非常有用的东西。比如这段代码,会有一个编译器警告,告诉你你把一个方法标记为 async
但它会同步运行。
TCPIP套接字对于初学者来说是非常复杂的。哼,对于高级开发者来说是非常复杂的。异步代码也很复杂,异步套接字更是复杂的火烧眉毛。
所以,对于你的情况,既然你已经有了解决方法,我建议你使用 Task.Run
来将现有的同步代码推送给线程池线程。对于UI应用来说,这是一个可以接受的模式,但是对于任何类型的服务器应用(例如ASP.NET)来说,你都不希望这样做。
public async Task push() {
...
var progress = new Progress<string>(report => listBox1.Items.Add(report));
await Task.Run(() => sendFiles(folder, progress));
listBox1.Items.Add(".");
listBox1.Items.Add(".");
listBox1.Items.Add("Files sent!");
...
}
public void sendFiles(DirectoryInfo dir, IProgress<string> progress) {
...
foreach (FileInfo file in files) {
server.sendFile(path + file.Name, folder.FullName.Replace(folder.Name,""));
progress?.Report("Sent file: " + file.Name);
}
foreach (DirectoryInfo subDir in dirs) {
sendFiles(subDir);
}
}
public void sendFile(string filePath, string root) {
...
}
这不是一个生产质量的解决方案,但它应该是一个可以让你开始实现的模式。