我知道 c# 和 asp.net 核心的基础知识,但是我需要一些有关事件处理程序的帮助。我正在尝试构建一个将推文流式传输到前端的 asp.net 核心应用程序。我使用 tweetinvi 库来获取推文和信号器来进行流式传输。
我在控制台应用程序中测试了 tweetinvi 并且它有效。我使用事件处理程序并在控制台上显示了推文流。同样的方法不适用于 asp.net 核心应用程序。但是,我设法将随机生成的数字流式传输到前端。所以我在前端的 js 代码和后端的流媒体集线器设置工作正常。
namespace TwitterWebApp
{
public class StreamHub : Hub
{
public ChannelReader<string> GetRandomNumber(int count, CancellationToken cancellationToken)
{
var channel = Channel.CreateUnbounded<string>();
StartTwitterStream(channel.Writer, count, cancellationToken);
//_ = StreamRandomNumbers(channel.Writer, 100, cancellationToken);
return channel.Reader;
}
private async Task StreamRandomNumbers(ChannelWriter<string> channelWriter, int count, CancellationToken cancellationToken)
{
var randomNumber = new Random();
for (var i = 0; i < count; i++)
{
cancellationToken.ThrowIfCancellationRequested();
await channelWriter.WriteAsync(Convert.ToString(randomNumber.Next()), cancellationToken);
}
channelWriter.TryComplete();
}
private void StartTwitterStream(ChannelWriter<string> channelWriter, int count, CancellationToken cancellationToken)
{
Auth.SetUserCredentials("xxx", "xxx", "xxx", "xxx");
var stream = Stream.CreateSampleStream();
stream.AddTweetLanguageFilter(LanguageFilter.English);
stream.TweetReceived += async (sender, e) =>
{
var tweet = e.Tweet.Text;
cancellationToken.ThrowIfCancellationRequested();
await channelWriter.WriteAsync(tweet, cancellationToken);
};
stream.StartStream();
}
}
}
获取推文需要事件处理程序实现,以便在收到每条推文后对其进行流式传输。在调试器中,我看到了推文及其内容。但是行:await channelWriter.WriteAsync(tweet,cancellationToken); 不向前端发送字符串。前端后端没有错误。
我将流作为一个类变量并检查了哈希码,它具有相同的值。所以看起来流没有被丢弃和关闭。
在调试模式下,TweetReceived 操作被无限调用并生成新的推文,但 WriteAsync 方法什么也不做。
后来,在开始时,当创建频道时,我添加了
channel.Writer.WriteAsync("ok", cancellationToken);
只是发送“ok”字符串。然而这个方法没有被执行,当
stream.StartStream();
稍后调用。我觉得很奇怪为什么稍后调用 StartStream 时 WriteAsync 不起作用。删除 StartStream 使 WriteSync 工作得很好。
public class StreamHub : Hub
{
public ISampleStream stream;
public ChannelReader<string> GetRandomNumber(int count, CancellationToken cancellationToken)
{
var channel = Channel.CreateUnbounded<string>();
channel.Writer.WriteAsync("ok", cancellationToken);
Auth.SetUserCredentials("xxx", "xxx", "xxx", "xxx");
stream = Stream.CreateSampleStream();
stream.AddTweetLanguageFilter(LanguageFilter.English);
StartTwitterStream(channel.Writer, cancellationToken);
return channel.Reader;
}
private void StartTwitterStream(ChannelWriter<string> channelWriter, CancellationToken cancellationToken)
{
stream.TweetReceived += (sender, e) =>
{
var streamHashCode1 = sender.GetHashCode();
var tweet = e.Tweet.Text;
cancellationToken.ThrowIfCancellationRequested();
channelWriter.WriteAsync(tweet, cancellationToken);
};
var streamHashCode2 = stream.GetHashCode();
stream.StartStream();
}
}