gpt4 book ai didi

c# - 如何在 C# UWP 中暂停一个线程同时继续其他线程

转载 作者:行者123 更新时间:2023-11-30 20:28:27 24 4
gpt4 key购买 nike

我正在构建一个应用程序,它将连接到 Twitter,接收推文数据并将它们存储到数据库中。之后,应用程序会从数据库中检索数据,分析内容,如果有与另一个预先设置的数据库匹配的内容,则会弹出一个toast通知。

一共有5个任务需要同时运行。

Task 1 => GetKeyword method (Get keyword list from database)

Task 2 => Connect method (Connect to Twitter and stream data filtered by the keyword and store into database)

Task 3 => RetrieveData method (Retrieve stored streamed data from database)

Task 4 => Analyze method (Analyze the tweet content and found matching content)

Task 5 => Notify method (If there is a match, notify the user by pop up toast notification)

所以之前我设法让它们一起运行,但是使用这些代码有时它会永远停留在 Connect 任务并且不会继续执行 RetrieveData 任务和 分析任务。

如何限制 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();
}

这是连接方法代码:

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 应用程序,此代码位于按钮后面。

最佳答案

如评论中所述,直接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)

关于c# - 如何在 C# UWP 中暂停一个线程同时继续其他线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47378974/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com