我正在构建一个连接到Twitter的应用程序,接收推文数据并将它们存储到数据库中。之后,应用程序将从数据库中检索数据,分析内容,如果与另一个预设数据库有匹配的内容,则会弹出一个Toast通知。
总共将有5个任务需要同时运行。
任务1 => GetKeyword方法(从数据库中获取关键字列表)
任务2 =>连接方法(连接到Twitter并流式传输由关键字过滤的数据并存储到数据库中)
任务3 => RetrieveData方法(从数据库中检索存储的流数据)
任务4 =>分析方法(分析推文内容并找到匹配内容)
任务5 =>通知方法(如果匹配,请通过弹出Toast通知通知用户)
所以以前我设法让它们完全运行,但是对于这些代码,有时它会永远停留在Connect
任务,并且不会继续执行RetrieveData
任务和Analyze
任务。
如何限制Connect
任务的运行时间并让它继续执行RetrieveData
任务和Analyze
任务?我已经限制了存储在方法本身内的流数据的数量,但它似乎只停止了流本身而不是线程。
这是多线程的代码:
List<string> streamdata = new List<string>();
List<string> keyList = new List<string>();
try
{
var task = Task.Run(() => GetKeyword(0))
.ContinueWith(prevTask => Connecting(1000, keyList))
.ContinueWith(prevTask => RetrieveData(1500))
.ContinueWith(prevTask => MakeRequest(2000, streamdata))
.ContinueWith(prevTask => Notify(2500, cyberbully, notification));
task.Wait();
}
catch (Exception ex)
{
MessageDialog messagebox = new MessageDialog("Task running error:" + ex);
await messagebox.ShowAsync();
}
这是Connect方法代码:
public static void Connecting(int sleepTime, List<string> keyList)
{
//Set the token that provided by Twitter to gain authorized access into Twitter database
Auth.SetUserCredentials("YTNuoC9rrJs8g9kZ0hRweKrpp", "wXj6VSl68jeFStRWHDnhG19oP1WZGeBFMNgT3KCkI6MaX46SMT", "892680922322960384-8ka1NuhgiuxjSLUffQVdwmnOIbIduZa", "y92ycGrGCJS9vBJU79gq34rV6FCwNjBPFFOqhEHaTQe1l");
//Create stream with filter stream type
var stream = Stream.CreateFilteredStream();
int numoftweet = 0;
//Set language filter to English only
stream.AddTweetLanguageFilter(LanguageFilter.English);
//Connect to database that stored the keyword
foreach (var key in keyList)
{
stream.AddTrack(key);
}
//Let the stream match with all the conditions stated above
stream.MatchingTweetReceived += async (sender, argument) =>
{
//Connect to MongoDB server and database
var tweet = argument.Tweet;
try
{
var client = new MongoClient();
var database = client.GetDatabase("StreamData");
var collection = database.GetCollection<BsonDocument>("StreamData");
//Exclude any Retweeted Tweets
if (tweet.IsRetweet) return;
//Store the data as a BsonDocument into MongoDB database
var tweetdata = new BsonDocument
{
//Store only the data that needed from a Tweet
{"Timestamp", tweet.TweetLocalCreationDate},
{"TweetID", tweet.IdStr},
{"TweetContent",tweet.Text},
{"DateCreated", tweet.CreatedBy.CreatedAt.Date},
{"UserID", tweet.CreatedBy.IdStr},
{"Username", tweet.CreatedBy.Name}
};
//Insert data into MongoDB database
await collection.InsertOneAsync(tweetdata);
//Every tweets streamed, add 1 into the variable
numoftweet += 1;
//If the number of tweets exceed 100, stopped the stream
if (numoftweet >= 100)
{
stream.StopStream();
}
}
//Catch if any exception/errors occured
catch (Exception ex)
{
MessageDialog messagebox = new MessageDialog("MongoDB Connection Error:" + ex);
await messagebox.ShowAsync();
}
};
//Start the stream
stream.StartStreamMatchingAllConditions();
}
备注:这是一个UWP应用程序,此代码位于按钮后面。
答案 0 :(得分:3)
正如评论中所述,只需直接await
您的方法,而不添加Task.Run
(看起来您的方法没有返回任何内容):
await GetKeyword(0);
await Connecting(1000, keyList);
await RetrieveData(1500);
await MakeRequest(2000, streamdata);
await Notify(2500, cyberbully, notification);
旁注:不要将async void
用于您的方法,它仅适用于事件处理程序。如果您的方法没有返回任何内容,请使用async Task
:
public static async Task Connecting(int sleepTime, List<string> keyList)
答案 1 :(得分:1)