我了解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();
}
}
}
获取tweet需要事件处理程序的实现,以便在接收到每个tweet时流式传输。在调试器中,我看到tweet及其内容。但是行:等待channelWriter.WriteAsync(tweet,cancellingToken);不会将字符串发送到前端。前端后端没有错误。
我将流设为类变量并检查了哈希码,并且它具有相同的值。因此,看起来流没有被浪费掉并关闭。
在调试模式下,将无限调用TweetReceived动作并生成新的tweet,但WriteAsync方法不执行任何操作。
稍后,在开始的时候,我创建了频道,
channel.Writer.WriteAsync("ok", cancellationToken);
只需发送“确定”字符串。但是,当
时,不会执行此方法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();
}
}