[英]Get SelectedIndex from custom non-UI thread
我的應用程序代碼遇到問題。 我將其設計為從 web 下載.xml
文件並閱讀此 XML 文件,以便下載包含其中數據的多個文件。 但是,我已將我的應用程序編程為同步的,並且根本無法正常工作,因此我試圖將我的程序更改為在處理此任務時主要以異步方式工作。 我希望應用程序在新線程上運行此方法,但在獲取位於 UI 線程上的 ReposListBox 的選定索引時遇到錯誤。 它給了我一個System.InvalidOperationException
,因為我試圖訪問第 13 行上的選定索引 => int index = ReposListBox.SelectedIndex;
. 我應該如何將所選索引放入此 integer 而不產生異常。
我真的很絕望,謝謝你的幫助:)
private void syncButton_Click(object sender, RoutedEventArgs e) {
Thread thread = new Thread(Synchronize);
thread.Start();
}
private void Synchronize() {
try {
var m_Manager = new Mods();
var f_Synchronization = new FileSynchronization();
var r_ListHandler = new RepositoryListHandler();
// Download XML file and call VerifyModpacks();
int index = ReposListBox.SelectedIndex;
m_Manager.DownloadRepository(repos[index].Modpacks.Modpack.Source + "/index.xml");
m_Manager.VerifyModpacks();
m_Manager.LoadModpack(repos[index].Modpacks.Modpack.ID);
for (int i = 0; i < repos[index].Addons.Addon.Count; i++) {
m_Manager.VerifyMod(repos[index].Modpacks.Modpack.ID, i);
}
} catch (Exception ex) {
Trace.WriteLine("[Synchronize] Task Failed :: Exception [" + ex + "] thrown.");
}
}
您需要在 GUI 線程上調用 GUI 元素。 通常,最好在事件處理程序中阻止 GUI 時執行此操作,以防止在線程運行時用戶更改 GUI 時出現任何可能的競爭條件。
private void syncButton_Click(object sender, EventArgs e)
{
var thread = new Thread(Synchronize);
thread.Start(ReposListBox.SelectedIndex);
// Or use an object or struct to pass along more than one object to the thread.
}
void Synchronize(object data)
{
var selectedIndex = (int)data;
Console.WriteLine(selectedIndex);
}
但是,對於快速 n 臟解決方案,您可以在Invoke
GUI 線程上的一些幫助代碼時阻塞線程:
void Synchronize(object data)
{
int orSelectedIndex = 0;
// Invoke a small Lambda on the GUI thread to get the index
Invoke(new MethodInvoker(() =>
{
orSelectedIndex = ReposListBox.SelectedIndex;
}));
// Use our local variable in the thread
Console.WriteLine(orSelectedIndex);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.