C#任务阻塞UI
问题描述:
我有这样的代码,反序列化JSON的网址,但GUI仍然被封锁,我不知道如何将它整理出来C#任务阻塞UI
**多少钱,我必须以写stackoverflow让我发布的东西? “看起来你的文章主要是代码,请添加更多的细节。”
按钮代码:
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
方法,你也应该使用伺机通过从Web客户端下载您的字符串数据将其更改为:
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方法,您可以自动将任务展开到布尔,然后您可以继续在UI线程上执行代码。
谢谢它现在适用于一些调整。我使用DownloadStringTaskAsync而不是DownloadStringAsync – lorigio 2013-04-06 17:15:19