我不确定这是否是合适的地方,但这个网站在其他方面对我来说一直是一种极好的帮助。
我正在编写一个小型的个人Winforms应用程序中有一个完美的背景线程候选者,我正在寻求帮助,试图正确/正确地实现它。
这是来自表示层的调用:
private void btnGetSeasonSchedule_Click(object sender, EventArgs e){
Cursor.Current = Cursors.WaitCursor;
objSchedule.RetreiveSeasonSchedule();
MessageBox.Show("Finished");
Cursor.Current = Cursors.Default;
}
这是BLL中的代码:
public class SeasonSchedule{
public ForumAssistantDAL.SeasonSchedule objSchedule = new ForumAssistantDAL.SeasonSchedule();
public void RetreiveSeasonSchedule(){
DataTable dtData = GetGamesInRange(DateTime.Parse("2015-10-07"), DateTime.Parse("2016-04-30"));
// this call is to an SQLBulkUpdate function in the DAL
objSchedule.UploadSchedule(dtData);
}
// ***** BackgroundWorker Candidate #1 *****
// my first thought is to have the entire function below as a backgroundworker process
//as it is used in a few other locations in the application *****
private DataTable GetGamesInRange(DateTime startDate, DateTime endDate){
DataTable dtScheduleTable = objSchedule.CreateScheduleTable();
// ***** BackgroundWorker Candidate #1 *****
// instead of the entire function, just put this ForEach loop in a BackgroundWorker
foreach (DateTime day in EachDay(DateTime.Parse(startDate.ToString("yyyy-MM-dd")), DateTime.Parse(endDate.ToString("yyyy-MM-dd")))){
//build proper URL using URIBuilder
//...URL requires a formatted date, hence the necessity of re-building it in a foreach loop
var uriBuilder = new UriBuilder();
uriBuilder.Scheme = "http";
uriBuilder.Host = "my.datasource.address";
uriBuilder.Path = "path_part_1/path_part_2/" + day.ToString("yyyy-MM-dd") + ".jsonp";
var uri = uriBuilder.Uri;
try{
string json = new WebClient().DownloadString(uri);
json = json.Replace("loadScoreboard(", "");
json = json.Replace(")", "");
GameCollection gameDay = objSchedule.ParseGames(json);
// ***** BackgroundWorker Candidate #2 *****
// each GameCollection can contain from zero to N games
// each game is added to a temporary DataTable
// when the ForEach loop is complete, the entire DataTable is returned, and the DataTable is SQLBulkCopy-ied to the database server
foreach (DeserializedGame game in gameDay.Games){
objSchedule.InsertGame(game, dtScheduleTable, day);
}
}
catch (WebException ex){
if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null){
var resp = (HttpWebResponse)ex.Response;
if (resp.StatusCode == HttpStatusCode.NotFound){
// HTTP 404 - the page was not found, continue with next in the for loop
continue;
}
}
//throw any other exception - this should not occur
throw;
}
}
return dtScheduleTable;
}
private IEnumerable<DateTime> EachDay(DateTime from, DateTime thru){
for (var day = from.Date; day.Date <= thru.Date; day = day.AddDays(1))
yield return day;
}
}
我的目标如下:
我已经看过ThreadStart和ParameterizedThreadStart(我相信它是正确使用的),但是当我正确和正确地实现线程时,我觉得我非常失败。线程对我来说是一个新概念,所以任何&#34;对于假人而言#34;非常感谢您提供的帮助。