我該如何使用它?
我正在開發一個程式,該程式專注于處理檔案和目錄,并在 DataGridView 中顯示有關檔案的資訊。那和復制檔案,基本上是它所做的兩件事。
現在,當我嘗試“掃描”1-400 600mb-1.6gb iso、檔案等的串列時。這變得很耗時,因為我必須檢索要在 DataGridView 中顯示的每個檔案的特定資訊。我有一個帶有屬性的強型別資料型別 Game,并且一切正常。我只是遇到了障礙,或者有一個金發的時刻。代表、回呼等對我來說都像是象形文字。我已經習慣了面對可怕的資料型別,我不知道該怎么辦。但是,當需要真正利用它并以正確的方式使用它時......是的,那里沒有正式的知識。
這有效..
private Task<IBindingList> getGamesTask(string folder)
{
string[] filters = new[] { "iso", "gcm" };
string[] files = GetFilesFolder(folder, filters, true).Result;
var source = new BindingSource();
IBindingList games = new BindingList<Game>();
for (int j = 0; j < files.Length; j )
{
var file = files[j];
games[j] = GetGameInfo(files[j]);
}
return FromResult(games);
}
我想做到(我認為......)這個:
//Call from elsewhere
{
var progress = new Progress<int>(value => {
pbCopy.Value = i > pbCopy.Maximum ? pbCopy.Maximum : i;
}});
await Task.Run(() = getGamesTask(folder, progress));
}
private Task<IBindingList> getGamesTask(string folder, IProgress<int> i)
{
string[] filters = new[] { "iso", "gcm" };
string[] files = GetFilesFolder(folder, filters, true).Result;
var source = new BindingSource();
IBindingList games = new BindingList<Game>();
for (int j = 0; j < files.Length; j )
{
var file = files[j];
games[j] = GetGameInfo(files[j]);
i?.Report(j);
}
return FromResult(games);
}
取自:
這個堆疊問題
var progress = new Progress<int>(value => { progressBar.Value = value; });
await Task.Run(() => GenerateAsync(progress));
void GenerateAsync(IProgress<int> progress)
{
...
progress?.Report(13);
...
}
因此,每次迭代 i?.Report(j) 都應該點擊進度條并更新它。對嗎?...它可以編譯,但我無法讓它...好吧。實際作業或更新進度條。我在新的領域,老實說,我幾乎不知道從這里去哪里。嘗試進一步了解異步編程,執行緒等。至少學習一些新東西..但是..正確的方法,不只是,呵呵那行得通。涼爽的。只有那些知道自己在做什么的人才會因為你那樣做而失去理智。
重新提出的問題:如何獲取此代碼或類似代碼以在每次迭代中使用 int 來點擊我的進度條?
安迪的第一個答案是有效的。這行得通,它只是沒有在 UI 執行緒上運行。所以..我丟失了評論/片段,你必須檢查是否需要呼叫,并使用progressBar.BeginInvoke。
@Andy,如果您可以重新添加該片段,那很可能是其他人正在尋找的。這就是我……而且……它現在已經消失了:P
uj5u.com熱心網友回復:
我將在這里冒險并假設您不在 UI 執行緒上。
嘗試更改此行:
var progress = new Progress<int>(value => { progressBar.Value = value; });
對此:
var progress = new Progress<int>(value =>
{
// are we outside the UI thread?
if (progressBar.InvokeRequired)
{
// yes we are, post it to the UI thread to process
progressBar.Invoke(new Action(() => progressBar.Value = value));
return;
}
// no we aren't. We are in the UI thread. Execute it now.
progressBar.Value = value;
});
任何時候修改 UI,都必須從 UI 執行緒完成。呼叫Invokeany將在所述 UI 執行緒上Control執行delegate(在本例中為 an )。Action檢查您當前InvokeRequired是否正在從 UI 執行緒執行。
我相信這是正在發生的事情的原因是你正在使用Task......那些可以在 UI 背景關系之外執行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/506808.html
