如何将此代码设置为异步,我不知道异步如何与FTP上传一起使用。我尝试了很多东西,但是如果你上传文件,我不知道在哪里放'等待'。
public static async void SelectRectangle(Point SourcePoint, Point DestinationPoint, Rectangle SelectionRectangle, string FilePath)
{
using (Bitmap bitmap = new Bitmap(SelectionRectangle.Width, SelectionRectangle.Height))
{
using (Graphics g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(SourcePoint, DestinationPoint, SelectionRectangle.Size);
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(Properties.Settings.Default.ftphost + Properties.Settings.Default.ftppath + FilePath + "." + Properties.Settings.Default.extension_plain);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(Properties.Settings.Default.ftpuser, Properties.Settings.Default.ftppassword);
request.UseBinary = true;
bitmap.Save(request.GetRequestStream(), ImageFormat.Png);
}
}
}
Joery。
答案 0 :(得分:6)
您需要创建方法async
,然后使用await
进行任何异步操作。您似乎只有其中一个,因此以下内容应该有效:
public static async Task SelectRectangle(Point SourcePoint, Point DestinationPoint, Rectangle SelectionRectangle, string FilePath)
{
using (Bitmap bitmap = new Bitmap(SelectionRectangle.Width, SelectionRectangle.Height))
{
using (Graphics g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(SourcePoint, DestinationPoint, SelectionRectangle.Size);
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(Properties.Settings.Default.ftphost + Properties.Settings.Default.ftppath + FilePath + "." + Properties.Settings.Default.extension_plain);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(Properties.Settings.Default.ftpuser, Properties.Settings.Default.ftppassword);
request.UseBinary = true;
Stream rs = await request.GetRequestStreamAsync();
bitmap.Save(rs, ImageFormat.Png);
}
}
}