我有以下代码将文件上传到服务器并在栏中更新上传进度。
private void UploadButton_Click(object sender, EventArgs e)
{
Cursor = Cursors.WaitCursor;
try
{
// get some info about the input file
System.IO.FileInfo fileInfo = new System.IO.FileInfo(FileTextBox.Text);
UploadDocument(fileInfo);
// show start message
LogText("Starting uploading " + fileInfo.Name);
LogText("Size : " + fileInfo.Length);
}
catch (Exception ex)
{
LogText("Exception : " + ex.Message);
if (ex.InnerException != null) LogText("Inner Exception : " + ex.InnerException.Message);
}
finally
{
Cursor = Cursors.Default;
}
}
private async void UploadDocument(System.IO.FileInfo fileInfo)
{
var someTask = await Task.Run<bool>(() =>
{
// open input stream
using (System.IO.FileStream stream = new System.IO.FileStream(FileTextBox.Text, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
using (StreamWithProgress uploadStreamWithProgress = new StreamWithProgress(stream))
{
uploadStreamWithProgress.ProgressChanged += uploadStreamWithProgress_ProgressChanged;
// start service client
FileTransferWCF.FileTransferServiceClient client = new FileTransferWCF.FileTransferServiceClient();
//FileTransferClient.FileTransferServiceClient client = new FileTransferClient.FileTransferServiceClient();
// upload file
client.UploadFile(fileInfo.Name, fileInfo.Length, uploadStreamWithProgress);
LogText("Done!");
// close service client
client.Close();
}
}
return true;
});
}
void uploadStreamWithProgress_ProgressChanged(object sender, StreamWithProgress.ProgressChangedEventArgs e)
{
if (e.Length != 0)
progressBar1.Value = (int)(e.BytesRead * 100 / e.Length);
}
我收到错误消息:“跨线程操作无效:控件'progressBar1'从创建它的线程以外的线程访问。” 在行中:
progressBar1.Value = (int)(e.BytesRead * 100 / e.Length);
也许我做错了。我是 .Net 任务库的新手。
有什么线索吗?