如何在监听Firestore数据库时保持控制台应用程序打开



我有一个简单的函数来监听firestore数据库的变化,代码如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Google.Cloud.Firestore;
namespace Firestore2
{
class Program
{
static async Task Main(string[] args)
{
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", "credentials.json");
FirestoreDb db = FirestoreDb.Create("example");
Console.WriteLine("Success");

// Create a random document ID. The document doesn't exist yet.
DocumentReference doc = db.Collection("new").Document();
FirestoreChangeListener listener = doc.Listen(snapshot =>
{
Console.WriteLine($"Callback received document snapshot");
Console.WriteLine($"Document exists? {snapshot.Exists}");
if (snapshot.Exists)
{
Console.WriteLine($"Value of 'value' field: {snapshot.GetValue<int?>("value")}");
}
Console.WriteLine();
});   
}
}
}

一切工作正常,但程序关闭后运行一次监听器。我还是c#的新手,我想象侦听器部分将保持程序运行,但我错了。我怎样才能让它继续运行呢?希望不要使用循环

FirestoreChangeListener提供一个属性ListenerTask和一个方法StopAsync()。参见https://cloud.google.com/dotnet/docs/reference/Google.Cloud.Firestore/latest/Google.Cloud.Firestore.FirestoreChangeListener。

我会尝试下面的方法:

private static async Task Main(string[] args)
{
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", "credentials.json");
FirestoreDb db = FirestoreDb.Create("example");
Console.WriteLine("Success");
// Create a random document ID. The document doesn't exist yet.
DocumentReference doc = db.Collection("new").Document();
FirestoreChangeListener listener = doc.Listen(snapshot =>
{
Console.WriteLine($"Callback received document snapshot");
Console.WriteLine($"Document exists? {snapshot.Exists}");
if (snapshot.Exists)
{
Console.WriteLine($"Value of 'value' field: {snapshot.GetValue<int?>("value")}");
}
Console.WriteLine();
});
// Handle CTRL+C (SIGINT)
Console.CancelKeyPress += (sender, e) =>
{
// The current process should resume when the event handler concludes
e.Cancel = true;
listener.StopAsync();
};
await listener.ListenerTask;
}

相关内容

最新更新