c#任务阻塞ui
本文关键字:ui 任务 | 更新日期: 2023-09-27 18:07:53
我有这个代码从url反序列化JSON,但GUI仍然被阻止,我不知道如何排序。
按钮代码:
private void button1_Click(object sender, EventArgs e)
{
var context = TaskScheduler.FromCurrentSynchronizationContext();
string RealmName = listBox1.Items[listBox1.SelectedIndex].ToString();
Task.Factory.StartNew(() => JsonManager.GetAuctionIndex().Fetch(RealmName)
.ContinueWith(t =>
{
bool result = t.Result;
if (result)
{
label1.Text = JsonManager.GetAuctionIndex().LastUpdate + " ago";
foreach (string Owner in JsonManager.GetAuctionDump().Fetch(JsonManager.GetAuctionIndex().DumpURL))
{
listBox2.Items.Add(Owner);
}
}
},context));
}
获取和反序列化函数
public async Task<bool> Fetch(string RealmName)
{
using (WebClient client = new WebClient())
{
string json = "";
try
{
json = client.DownloadString(new UriBuilder("my url" + RealmName).Uri);
}
catch (WebException)
{
MessageBox.Show("");
return false;
}
catch
{
MessageBox.Show("An error occurred");
Application.Exit();
}
var results = await JsonConvert.DeserializeObjectAsync<RootObject>(json);
TimeSpan duration = DateTime.Now - Utilities.UnixTimeStampToDateTime(results.files[0].lastModified);
LastUpdate = (int)Math.Round(duration.TotalMinutes, 0);
DumpURL = results.files[0].url;
return true;
}
}
在您的Fetch
方法中,您还应该使用await从WebClient下载字符串数据,将其更改为:
json = await client.DownloadStringAsync(new UriBuilder("my url" + RealmName).Uri);
而不是使用Task
与延续你应该使用等待也在你的按钮事件处理程序:
private async Task button1_Click(object sender, EventArgs e)
{
string RealmName = listBox1.Items[listBox1.SelectedIndex].ToString();
bool result = await JsonManager.GetAuctionIndex().Fetch(RealmName);
if (result)
{
label1.Text = JsonManager.GetAuctionIndex().LastUpdate + " ago";
foreach (string Owner in await JsonManager.GetAuctionDump().Fetch(JsonManager.GetAuctionIndex().DumpURL))
{
listBox2.Items.Add(Owner);
}
}
}
现在由c#编译器设置延续。默认情况下,它将在UI线程上继续,因此您不必手动捕获当前同步上下文。通过等待Fetch方法,您可以自动将Task展开为bool,然后您可以继续在UI线程上执行代码。