当我无权访问用于检索数据的客户端库时,我试图了解异步获取一组数据的正确代码。我指定了一个端点和一个日期范围,我应该检索一个播放列表列表。在 Start() 调用之后,我现在再也没有回来过。注意:这是在 WinForm 中运行的。我试图更好地理解任务,而不只是想跳到等待或 BackgroundWorker。我知道我在某个地方迷路了。
private void GoButtonClick(object sender, EventArgs e)
{
string baseUrl = "http://someserver/api";
var startDateTime = this._startDateTimePicker.Value;
var endDateTime = this._endDateTimePicker.Value;
_getPlaylistsFunc = delegate()
{
var client = new PlaylistExportClient(baseUrl);
return client.GetPlaylistsByDateRange(startDateTime, endDateTime).ToList();
};
var task = new Task<List<Playlist>>(_getPlaylistsFunc);
task.ContinueWith((t) => DisplayPlaylists(t.Result));
task.Start();
}
private void DisplayPlaylists(List<Playlist> playlists)
{
_queueDataGridView.DataSource = playlists;
}
更新 我做了这些更改,但现在应用程序似乎挂起 UI 线程。
private void GoButtonClick(object sender, EventArgs e)
{
string baseUrl = "http://someserver/api";
var startDateTime = this._startDateTimePicker.Value;
var endDateTime = this._endDateTimePicker.Value;
var token = Task.Factory.CancellationToken;
var context = TaskScheduler.FromCurrentSynchronizationContext();
Task.Factory.StartNew(() =>
{
var client = new PlaylistExportClient(baseUrl);
_queueDataGridView.DataSource = client.GetPlaylistsByDateRange(startDateTime, endDateTime).ToList();
},token,TaskCreationOptions.None,context);
}