我有这个类:
public class UploadFile : INotifyPropertyChanged {
private string name;
public string Name {
get {
return name;
}
set {
name = value;
OnPropertyChanged("Name");
}
}
private FileInfo fileInfo;
public FileInfo FileInfo { get; set; }
private string length;
public string Length {
get {
return length;
}
set {
length = value;
OnPropertyChanged("Length");
}
}
private int percentage;
public int Percentage {
get {
return percentage;
}
set {
percentage = value;
OnPropertyChanged("Percentage");
}
}
public string ProgressValue {
get { return string.Format("{0}%", Percentage); }
}
private string imageSource;
public string ImageSource {
get {
return imageSource;
}
set {
imageSource = value;
OnPropertyChanged("ImageSource");
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
private void OnPropertyChanged(string property) {
if (PropertyChanged != null) {
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}
我正在尝试创建一个能够上传大文件和多个文件的文件上传功能。我使用了一个Web服务来实现这个功能。我已经在我的用户界面中进行了双向绑定,现在我想要上传这些文件。我将使用以下代码来实现:
private void DoUpload() {
foreach (UploadFile file in fileInfos){
int BUFFERSIZE = 1024;
int offset = 0; //get from webservice, when partial file
FileStream s = file.FileInfo.OpenRead();
byte[] buffer = null;
long remainingBytes = s.Length - offset;
while (remainingBytes > 0) {
if (remainingBytes < BUFFERSIZE) {
buffer = new byte[remainingBytes];
BUFFERSIZE = (int)remainingBytes;
}
else if (remainingBytes > BUFFERSIZE) {
buffer = new byte[BUFFERSIZE];
}
s.Read(buffer, 0, BUFFERSIZE);
//push to webservice
Thread.Sleep(20);
//UploadService.Service1SoapClient client = new MultiLargeFileUpload.UploadService.Service1SoapClient();
//client.LargeUploadCompleted +=new EventHandler<AsyncCompletedEventArgs>(client_LargeUploadCompleted);
//client.LargeUploadAsync(1, buffer, file.Name);
offset += BUFFERSIZE;
int newPercentage = offset / (int)file.FileInfo.Length * 100;
file.Percentage = newPercentage;
remainingBytes = s.Length - offset;
}
//file.Percentage = 100;
//file.ImageSource = "accept.png";
}
}
问题在于我无法更新UI,或者说跨线程操作。我尝试使用了Dispatcher,但是并没有成功,因为我不知道在哪里插入它。