我有以下代碼將文件上載到服務器並更新條上載的進度。用於上傳和更新進度的Task.Run返回錯誤
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新任務庫的新成員。
任何線索?
更妙的是,你可以使用'BeginInvoke',因爲你不需要等待調用的結果。 – 2013-02-25 16:33:02
^他說什麼。 – FlyingStreudel 2013-02-25 16:33:56
@MarekDzikiewicz所以它會像這樣:progressBar1.BeingInvoke(new Action(()=> {progressBar1.Value =(int)(e.BytesRead * 100/e.Length);})); ?? – VAAA 2013-02-25 16:45:35