Beginner Questions on Stream in WinForm

Oct 21, 2014 at 12:28 PM
Hello,

I'm completely new to this, so I'm curious if I can ask for help getting streams to work in a winform. For starters, I just want to try logging a stream, but I'd be satisfied with starting a stream without the winform hanging. Here's what I have:
         private void btnStartStream_Click(object sender, EventArgs e)
        {
            Console.WriteLine("** Start Stream has been clicked");
            
            var credentials = TwitterCredentials.CreateCredentials(accessToken, accessTokenSecret, myConsumerKey, myConsumerSecret);
            
            TwitterCredentials.ExecuteOperationWithCredentials(credentials, ()
                =>
            {
                var sampleStream = Stream.CreateSampleStream();
                sampleStream.TweetReceived += (s, a) => Console.WriteLine(a.Tweet.Text);
                sampleStream.StartStream();
            }); 

            Console.WriteLine("** Stream has been started");
        }
When I click my "Start Stream" button, this code launches. I never see "** Stream has been started" in the log. I can't get past sampleStream.StartStream(); using breakpoints. I'm sure I have a pretty basic misunderstanding of something here, but what could that possibly be?
Coordinator
Oct 22, 2014 at 4:54 PM
Hi,

This is normal, the StartStream method is a synchronous method that will exit only when the stream closes.
I believe you want your application to be running the stream in a BackgroundWorker or a new Thread instead of using the MainThread of your application.
var t = new Thread(() =>
{
    var sampleStream = Stream.CreateSampleStream();
    sampleStream.TweetReceived += (s, a) => Console.WriteLine(a.Tweet.Text);
    sampleStream.StreamStarted += (s, a) => Console.WriteLine("Stream started!");
    sampleStream.StartStream();
});

t.Start();
You can also notice that there is an event named StreamStarted to let you know when a Stream has successfully started to listen to Twitter Stream API.

Linvi
Marked as answer by linvi on 11/3/2014 at 9:43 AM
Coordinator
Oct 22, 2014 at 5:06 PM
Also, I usually prefer using TwitterCredentials.SetCredentials instead of TwitterCredentials.CreateCredentials + TwitterCredentials.ExecuteOperationWithCredentials.

Linvi