gpt4 book ai didi

c# - WPF C# : Using Tasks

转载 作者:太空狗 更新时间:2023-10-30 00:39:24 26 4
gpt4 key购买 nike

我已经阅读了一些不同的帖子,但我真的无法理解这个问题!

我有下面的类,当用户选择一个驱动器并设置 DriveInfo sel 时,DoUpload 方法运行,并将大量图像转换为字节格式。

现在这在我的机器上需要几秒钟,但是对于更多的图像和更慢的机器,它可能需要更长的时间,所以我想在另一个线程上执行此操作,但每次转换图像时,我想通知 UI,在我的如果我想更新以下属性:缩略图、文件名、步骤、上传进度。

同样,我想在每次转换图像时更新上述属性,如何使用任务 API 执行此操作?

这是类:

public class UploadInitiation : Common.NotifyUIBase
{
#region Public Properties
/// <summary>
/// File lists
/// </summary>
/// public ObservableCollection<BitmapImage> Thumbnail_Bitmaps { get; set; } = new ObservableCollection<BitmapImage>();
public ObservableCollection<ByteImage> Thumbnails { get; set; } = new ObservableCollection<ByteImage>();
public ObservableCollection<NFile> Filenames { get; set; } = new ObservableCollection<NFile>();

/// <summary>
/// Updates
/// </summary>
public ObservableCollection<UploadStep> Steps { get; set; } = new ObservableCollection<UploadStep>();
public int UploadProgress { get; set; } = 45;
public string UploadTask { get; set; } = "Idle...";
public bool UploadEnabled { get; set; } = false;

private bool _uploadBegin;
public bool UploadBegin
{
set { _uploadBegin = value; RaisePropertyChanged(); }
get { return _uploadBegin; }
}
#endregion END Public Properties

public UploadInitiation()
{
// Populate steps required, ensure upload returns UI updates
Steps.Add(new UploadStep { Message = "First task...", Complete = true, Error = null });
Steps.Add(new UploadStep { Message = "Error testing task...", Complete = false, Error = "testing error" });
Steps.Add(new UploadStep { Message = "Seperate upload to new thread...", Complete = false, Error = null });
Steps.Add(new UploadStep { Message = "Generate new file names...", Complete = false, Error = null });
Steps.Add(new UploadStep { Message = "Render Thumbnails, add to database...", Complete = false, Error = null });
Steps.Add(new UploadStep { Message = "Move images ready for print...", Complete = false, Error = null });
}

/// <summary>
/// This Method will perform the upload on a seperate thread.
/// Report progress back by updating public properties of this class.
/// </summary>
/// <param name="sel"></param>
public void DoUpload(DriveInfo sel)
{
// Check that there is a device selected
if (sel != null)
{
// Generate List of images to upload
var files = Directory.EnumerateFiles(sel.Name, "*.*", SearchOption.AllDirectories)
.Where(s => s.EndsWith(".jpeg") || s.EndsWith(".jpg") || s.EndsWith(".png"));

if (files.Count() > 0)
{
// Manage each image
foreach (string item in files)
{
// Generate thumbnail byte array
Thumbnails.Add(new ByteImage { Image = GenerateThumbnailBinary(item) });
}
foreach (string item in files)
{
// Generate new name
Filenames.Add(
new NFile
{
OldName = Path.GetFileNameWithoutExtension(item),
NewName = Common.Security.KeyGenerator.GetUniqueKey(32)
});
}
}
}
}

public byte[] GenerateThumbnailBinary(string loc)
{
BitmapImage image = new BitmapImage(new Uri(loc));

Stream stream = File.OpenRead(loc);
byte[] binaryImage = new byte[stream.Length];
stream.Read(binaryImage,0,(int)stream.Length);

return binaryImage;
}

最佳答案

有一个内置类 Progress它将向 UI 线程报告进度。

public async void StartProcessingButton_Click(object sender, EventArgs e)
{
// The Progress<T> constructor captures our UI context,
// so the lambda will be run on the UI thread.
var progress = new Progress<int>(percent =>
{
textBox1.Text = percent + "%";
});

// DoProcessing is run on the thread pool.
await Task.Run(() => DoProcessing(progress));
textBox1.Text = "Done!";
}

public void DoProcessing(IProgress<int> progress)
{
for (int i = 0; i != 100; ++i)
{
Thread.Sleep(100); // CPU-bound work
if (progress != null)
progress.Report(i);
}
}

阅读有关 Progress Reporter 的更多信息 here使用异步/等待。

更新 -

以下是您可以在代码中执行此操作以报告进度的方法。

使用其 progresschanged 处理程序定义进度对象。下面是一个带有匿名处理程序的示例。

  IProgress<UploadStep> progress = new Progress<UploadStep>(step =>
{
// sample consumption of progress changed event.
if (step.Complete)
{
// Do what ever you want at the end.
}
else
{
statusTxtBox.Text = step.Message;
}
});

用这个 Progress 对象调用你的 DoUpload

 DoUpload(driveInfo, progress);

现在在您的 DoUpload 方法中进行更改:

public void DoUpload(DriveInfo sel, IProgress<UploadStep> progress)
{
// Check that there is a device selected
if (sel != null)
{
progress.Report(new UploadStep { Message = "First Task..." });

// Generate List of images to upload
var files = Directory.EnumerateFiles(sel.Name, "*.*", SearchOption.AllDirectories)
.Where(s => s.EndsWith(".jpeg") || s.EndsWith(".jpg") || s.EndsWith(".png"));

if (files.Count() > 0)
{
// Manage each image
foreach (string item in files)
{
// Generate thumbnail byte array
Thumbnails.Add(new ByteImage { Image = GenerateThumbnailBinary(item) });
}

progress.Report(new UploadStep { Message = "Generated Thumnails..." });

foreach (string item in files)
{
// Generate new name
Filenames.Add(
new NFile
{
OldName = Path.GetFileNameWithoutExtension(item),
NewName = Common.Security.KeyGenerator.GetUniqueKey(32)
});
}

progress.Report(new UploadStep { Message = "Uplaoding to database..." });
}
}
}

关于c# - WPF C# : Using Tasks,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35899231/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com