我正在尝试将数据加载到组合框,并且当我运行表单而不进行调试时它正在工作。但是,当我尝试使用调试模式运行它时,出现错误:System.InvalidOperationException:“跨线程操作无效:从创建它的线程以外的线程访问控制“ResultBox”。” 我怎样才能解决这个问题?顺便说一句,有一个后台工作人员在下载数据时写入消息。我在某处读到可以使用后台工作人员解决此问题。这是表单代码:
public Form1()
{
InitializeComponent();
backgroundWorker1.WorkerReportsProgress = true;
}
private void Form1_Load(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private Task GetDataTask() {
return Task.Factory.StartNew(() => {
List<Result> results = new List<Result>();
results =
GetResults.GetData("http://worldcup.sfg.io/teams/results/");
foreach (var result in results)
{
ResultBox.Items.Add(result.Fifa_Code);
}
});
}
private void ResultBox_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void SaveTeam_Click(object sender, EventArgs e)
{
}
private async void backgroundWorker1_DoWork(object sender,
DoWorkEventArgs e)
{
await GetDataTask();
}
private void backgroundWorker1_ProgressChanged(object sender,
ProgressChangedEventArgs e)
{
resultsLoadedLabel.Text = (e.ProgressPercentage.ToString() + "%");
}
private void backgroundWorker1_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
resultsLoadedLabel.Text = "Podaci učitani!";
}
foreach 中的这行代码出现异常:
ResultBox.Items.Add(result.Fifa_Code);
这是获得结果的类:
public class GetResults
{
public static List<Result> GetData(string url) {
var client = new RestClient();
var request = new RestRequest(url, Method.GET);
request.AddHeader("User-Agent", "Nothing");
IRestResponse<List<Result>> results = client.Execute<List<Result>>
(request);
return results.Data;
}
}
繁华开满天机
相关分类