Skip to content

Commit fc4f7eb

Browse files
committed
Fixed "System.InvalidOperationException" being thrown with message: "Cross-thread operation not valid: Control 'myRichTextBox' accessed from a thread other than the thread it was created on.".
This would occur when a log messages was emitted from a non-UI-thread during Form construction, before the window handle was created. In these situations it is not sufficient to only check the richTextBox.InvokeRequired property as this would always return false - no matter what thread its on.
1 parent a7c24e6 commit fc4f7eb

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

Serilog.Sinks.RichTextBox.WinForms.Colored/Sinks/RichTextBoxForms/Extensions/RichTextBoxExtensions.cs

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818

1919
using System;
2020
using System.Runtime.InteropServices;
21+
using System.Threading;
2122
using System.Windows.Forms;
2223

2324
namespace Serilog.Sinks.RichTextBoxForms.Extensions
@@ -54,8 +55,25 @@ private struct Point
5455
private static extern IntPtr SendMessage(IntPtr hWnd, int wMsg, int wParam, ref Point lParam);
5556
#endif
5657

57-
public static void SetRtf(this RichTextBox richTextBox, string rtf, bool autoScroll)
58+
public static void SetRtf(this RichTextBox richTextBox, string rtf, bool autoScroll, CancellationToken token)
5859
{
60+
//Wait for richTextBox.Handle to be created
61+
if (!richTextBox.IsHandleCreated)
62+
{
63+
var mre = new ManualResetEventSlim();
64+
EventHandler eh = (sender, args) => mre.Set();
65+
richTextBox.HandleCreated += eh;
66+
try
67+
{
68+
if (richTextBox.IsHandleCreated) mre.Set();
69+
mre.Wait(token);
70+
}
71+
finally
72+
{
73+
richTextBox.HandleCreated -= eh;
74+
}
75+
}
76+
5977
if (richTextBox.InvokeRequired)
6078
{
6179
richTextBox.BeginInvoke(new Action(() => SetRtfInternal(richTextBox, rtf, autoScroll)));

Serilog.Sinks.RichTextBox.WinForms.Colored/Sinks/RichTextBoxForms/RichTextBoxSink.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,7 @@ private void ProcessMessages(CancellationToken token)
133133
{
134134
_renderer.Render(evt, builder);
135135
}
136-
_richTextBox.SetRtf(builder.Rtf, _options.AutoScroll);
136+
_richTextBox.SetRtf(builder.Rtf, _options.AutoScroll, token);
137137
lastFlush = DateTime.UtcNow;
138138
}
139139
}

0 commit comments

Comments
 (0)