Skip to content

Instantly share code, notes, and snippets.

@noseratio
Created February 7, 2022 05:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noseratio/6e1231a0b49329f979af63d59a0531c1 to your computer and use it in GitHub Desktop.
Save noseratio/6e1231a0b49329f979af63d59a0531c1 to your computer and use it in GitHub Desktop.
Streaming TextChanged event as IAsyncEnumerable
// verifying https://twitter.com/noseratio/status/1490181545746841602?s=20&t=9FIQA5E2Qz9oHLSEQIW7Ew
namespace textbox;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading.Channels;
static class Program
{
[STAThread]
static void Main()
{
ApplicationConfiguration.Initialize();
Application.Run(new MainForms());
}
}
public class TextBox: System.Windows.Forms.TextBox
{
public async IAsyncEnumerable<EventArgs> OnChanged(
[EnumeratorCancellation]
CancellationToken cancellationToken)
{
var channel = Channel.CreateUnbounded<EventArgs>();
void onTextChanged(object? _, EventArgs e) =>
channel.Writer.TryWrite(e);
this.TextChanged += onTextChanged;
try
{
await foreach (var ev in channel.Reader.ReadAllAsync(cancellationToken))
{
yield return ev;
}
}
finally
{
this.TextChanged -= onTextChanged;
channel.Writer.Complete();
}
}
}
public partial class MainForms : Form
{
public MainForms()
{
InitializeComponent();
var textBox = new TextBox() { Visible = true, Dock = DockStyle.Fill };
this.Controls.Add(textBox);
async Task OnChanged()
{
await foreach (var onChanged in textBox!.OnChanged(CancellationToken.None))
{
Trace.WriteLine("OnChanged");
}
}
_ = Task.Run(() => OnChanged());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment