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

How to pause a thread while continue others thread in C# UWP

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

总共有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 任务和 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();
}

这是连接方法代码:

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

How to pause a thread while continue others thread in C# UWP

您可以使用 ManualResetEvent

通知一个或多个等待线程事件已发生

reference

如评论中所述,直接执行 await 你的方法,而不添加 Task.Run (看起来你的方法没有 returning 任何东西):

await GetKeyword(0);
await Connecting(1000, keyList);
await RetrieveData(1500);
await MakeRequest(2000, streamdata);
await Notify(2500, cyberbully, notification);

旁注:不要将 async void 用于您的方法,它仅用于事件处理程序。如果你的方法没有 return 任何东西,那么使用 async Task:

public static async Task Connecting(int sleepTime, List<string> keyList)