Another option you have is to use Microsoft's Reactive Extension (Rx) to handle the asynchronicity for you.
Here's what your code could look like:
private SerialDisposable _subscription = new SerialDisposable();
private void button1_Click(object sender, EventArgs e)
{
string st = "hello my name is miroslav glamuzina";
string[] arr = st.Split(' ');
_subscription.Disposable =
Observable
.Interval(TimeSpan.FromMilliseconds(50.0))
.Select(i => arr[(int)i])
.Take(arr.Length)
.ObserveOn(this)
.Subscribe(word =>
{
label1.Text = word;
});
}
Now, the nice thing about this code is that the Subscribe
method returns an IDisposable
that can be used to stop the observable query before it finishes. Sort of like a cancellation request. Now by coupling this with a SerialDisposable
you get the nice behaviour that if your user clicks the button multiple times then only the latest subscription to the observable query will run and if an existing subscription is running it will be stopped first.
Rx also handles pushing code to a background thread without you neding to think about it. The ObserveOn(this)
call brings the thread back to running on the UI so that the label can be updated.