C# Cross threading. IRC stream thread to Main UI thread - c#

I've been trying to get this little IRC program working but for some reason I'm having issues with VS and cross threading. I'm not sure if I'm not doing it the proper way or what. Here are the parts causing the issue.
Main Thread:
public partial class MainUI : Form
{
private static IRC irc = new IRC();
public MainUI()
{
InitializeComponent();
}
public static void StartIRC()
{
irc.Start();
}
}
IRC Thread:
class IRC
{
private Thread ircThread;
private bool _running = true;
private NetworkStream stream;
private StreamWriter writer;
private StreamReader reader;
private TcpClient irc;
public IRC(){
ircThread = new Thread(new ThreadStart(Run));
ircThread.IsBackground = true;
}
public void Run(){
while (_running) {
parseInStream(reader.ReadLine());
}
}
public void Start()
{
ircThread.Start();
}
private void parseInStream(String inText)
{
String[] text = inText.Split(' ');
String name;
String message;
if (text[1].Equals("PRIVMSG")) {
name = capsFirstChar(getUser(inText));
message = inText.Substring(inText.IndexOf(":", 1) + 1);
sendToChatBox(capsFirstChar(name) + ": " + message, Color.Black);
}
else if (text[1].Equals("JOIN")) {
name = getUser(inText);
sendToChatBox(capsFirstChar(name) + " has joined the channel.", Color.LimeGreen);
}
else if (text[1].Equals("PART")) {
name = getUser(inText);
sendToChatBox(capsFirstChar(name) + " has left the channel.", Color.Red);
}
}
public void sendToChatBox(String text, Color color)
{
//Trying to send the text to the chatbox on the MainUI
//Works if the MainUI.Designer.cs file has it set to static
if (MainUI.txtMainChat.InvokeRequired) {
MainUI.txtMainChat.Invoke((MethodInvoker)delegate() {
sendToChatBox(text, color);
});
}
else {
MainUI.txtMainChat.SelectionColor = color;
MainUI.txtMainChat.AppendText(text);
}
}
private String getUser(String msg)
{
String[] split = msg.Split('!');
user = split[0].Substring(1);
return capsFirstChar(user);
}
private String capsFirstChar(String text)
{
return char.ToUpper(text[0]) + text.Substring(1).ToLower();
}
}
The only way I am able to get it to work is if I enter the MainUI.Designer.cs file and change the textbox to static and then change everything from this.txtMainChatto MainUI.txtMainChat.
My main problem is that when I make any changes on the visual side all the things labeled static or things named MainUI are deleted. I'm trying to figure out what I need to do to keep this from happening. Am I doing it the right way, or is there a better way? I tried using a background worker but it was using a lot of processing power to work that way for some reason.
I've looked around the web and can't seem to find out how one might relate to my setup. I see people calling a thread from the main thread and then sending things from the main thread to the thread it called but not the other way around. There is nothing else being written to the text box so there won't be an issue with it being used by two threads at the same time.

On my main UI thread I passed in "this" so I could reference the main window from my IRC Class. MainUI.txtMainChat
irc = new IRC(this);
Then in my IRC class
MainUI main;
public IRC(MainUI main){
this.main = main;
ircThread = new Thread(new ThreadStart(Run));
ircThread.IsBackground = true;
}
Then I was able to Change
//MainUI.txtMainChat to
main.txtMainChat
Like Cameron said, Though I know I was told it's not the best approach it gets me started.

Your designer file is rebuilt every time you change your UI in the designer.
You'll need to pass your MainUi to your IRC class, or give it an abstraction of it using an interface (best option).
public interface IMainUI
{
void AddText(string text, Color color);
void UiThread(Action code);
}
public class MainUI : IMainUI
{
// Whatever else
public void AddText(string text, Color color)
{
UiThread( () =>
{
// Same code that was in your Irc.SendToChatBox method.
});
}
public void UiThread(Action code)
{
if (InvokeRequired)
{
BeginInvoke(code);
return;
}
code.Invoke();
}
}
public class IRC
{
IMainUI _mainUi;
//Other properties, and fields
public IRC(IMainUI mainUi)
{
this._mainUi = mainUi;
// Other constructor stuff.
}
// Other logic and methods
}

Related

WPF RichTextBox.AppendText from another thread

I've got a WPF RichTextBox that I'd like to get working as a log output for the app.
I have a static class Log with method to write to the WPF RTB. Of course, this doesnt work when a background thread call the method.
I've tried using BeginInvoke, which works until the app gets closed throwing an error 'System.Windows.Application.Current.get returned null'
What is the proper approach to updating WPF RichText from other threads. And further, I dont think this background thread is disposing properly, any recommendations?
public partial class MainWindow : Window
{
Worker worker = new Worker();
public MainWindow()
{
InitializeComponent();
Log.rtb_control = rtbLog; // pass RTB ref to Log
worker.Start();
}
}
public static class Log
{
public static RichTextBox rtb_Control;
public static void Add(string Text)
{
App.Current.Dispatcher.BeginInvoke((Action)(() =>
{
rtb_Control.AppendText($"{Text}\r");
}
}
}
public class Worker
{
bool _Enabled = false;
public Worker()
{
_Manager = new Thread(new ThreadStart(Thread_Manager));
_Manager.Start();
}
public void Start()
{
_Enabled = true;
}
void Thread_Manager()
{
while(true)
{
if(_Enabled) { Log.Add("Inside Thread"); }
Thread.Sleep(10000);
}
}
}

send generated value from class to textbox

I have a library that generates strings to a function called MessageOut. This function, i cannot change the structure of.
It looks like this:
public void MessageOut(string msg) //params or return-type cannot be changed
{
Console.WriteLine(msg);
}
I have a textbox in my form that i want to show this message in.
How would I go about appending msg to that textbox?
I've tried:
public void MessageOut(string msg) //params or return-type cannot be changed
{
Console.WriteLine(msg);
sendMessageTextBox(msg);
}
public string[] sendMessageTextBox(params string[] msg)
{
string send = "";
foreach(var i in msg){send = i;}
return send;
}
Form:
private void getWaveformBtn_Click(object sender, EventArgs e)
{
MyClass className = new MyClass();
foreach(var i in className.sendMessageTextBox())
{
errorTextBox.Text += i;
}
}
For obvious reasons, this doesn't work ,but i'm unsure how to go about doing this. (i've tried: how to send text to textbox through a different class?
Sending information to a textbox from a class to a form)
However, i cannot seem to get those solutions to work.
Any help is much appreciated.
TL;DR - i basically want to show the new strings that messageOut recieves in a textbox
This can be done in may different ways, one of them will be to use a queue, fill it from MessageOut and drain it on button press.
public class MessageHandler /* , MessageOutInterface */
{
private readonly Queue<string> messages;
public MessageHandler()
{
this.messages = new Queue<string>();
}
public void MessageOut(string message)
{
this.messages.Enqueue(message);
}
public IEnumerable<string> PendingMessages()
{
string message;
while (this.messages.Count > 0)
yield return this.messages.Dequeue();
}
}
Your UI code
private void getWaveformBtn_Click(object sender, EventArgs e)
{
foreach(var i in messageHandler.PendingMessages())
{
errorTextBox.Text += i;
}
}
If MessageOut is called on one thread (i.e. not the main thread) and the button press obviously happens on the main thread you'll need a thread safe approach:
public class MessageHandler /* , MessageOutInterface */
{
private readonly object syncRoot = new Object();
private readonly Queue<string> messages;
public MessageHandler()
{
this.messages = new Queue<string>();
}
public void MessageOut(string message)
{
lock (this.syncRoot)
{
this.messages.Enqueue(message);
}
}
public IEnumerable<string> PendingMessages()
{
lock (this.syncRoot)
{
var pending = this.messages.ToArray();
this.messages.Clear();
return pending;
}
}
}
This is not the best way to synchronize the threads but you can ask another question about synchronization.

Backgroundworker updating log on the ui

I have a wpf application with a text box in the main window that is supposed to be used to display logging information while the user runs a long process.
<TextBox Grid.Row="1" Margin="10,10,10,10" AcceptsReturn="True" Name="txtLogging" TextWrapping="WrapWithOverflow"
Text="{Binding Path=LogText, Mode=TwoWay}" ScrollViewer.HorizontalScrollBarVisibility="Auto" ScrollViewer.VerticalScrollBarVisibility="Auto" />
public string LogText
{
get { return _logText; }
set
{
_logText = value;
OnPropertyChanged();
}
}
One of the buttons on the ui kicks off a process that takes a minimum of 30 seconds, and sometimes up to a few hours. Needless to say, running this on a background worker is preferred. The issue is that the logging class in the program is being created on the UI thread and has to be accessed during the worker's execution to update the UI with the log of what is currently happening.
The logger looks like this;
using System;
using System.IO;
namespace BatchInvoice
{
public enum LoggingLevel
{
Verbose = 0,
Info = 1,
Warning = 2,
Error = 3
}
public sealed class Logger
{
string _logFile;
static Logger() { }
public bool LogToDataBase = false;
public bool LogToFile = true;
public bool LogToScreen = false;
private Logger()
{
//string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string filePath = Directory.GetCurrentDirectory();
filePath = filePath + #"\LogFiles";
string extension = ".log";
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
/*string currentDir = Environment.CurrentDirectory;
DirectoryInfo directory = new DirectoryInfo(currentDir);
string fullDirectory = directory.FullName;*/
string date = (DateTime.Now).ToString("yyyyMMddHHmmss");
_logFile = filePath + "\\" + date + extension;
minimumLoggingLevel = LoggingLevel.Info;
}
private LoggingLevel minimumLoggingLevel;
public static void SetMinimumLoggingLevel(LoggingLevel minimum)
{
Instance.minimumLoggingLevel = minimum;
}
public static LoggingLevel GetMinimumLoggingLevel()
{
return Instance.minimumLoggingLevel;
}
private static readonly Logger instance = new Logger();
public static Logger Instance
{
get
{
return instance;
}
}
public static void Write(string content)
{
using (StreamWriter fileWriter = File.AppendText(Instance._logFile))
{
fileWriter.WriteLine(content);
}
}
public static void Write(string content, LoggingLevel warningLevel)
{
if (Instance.minimumLoggingLevel <= warningLevel)
{
if (Instance.LogToFile)
{
using (StreamWriter fileWriter = File.AppendText(Instance._logFile))
{
fileWriter.WriteLine(warningLevel.ToString() + ": " + content);
}
}
if (Instance.LogToScreen)
ScreenLogging.Write(content, warningLevel);
if (Instance.LogToDataBase)
{
//enter database loggign code here.
}
}
}
}
}
using System.Windows;
using System.Windows.Controls;
namespace BatchInvoice
{
public class ScreenLogging
{
private static ScreenLogging _instance;
private ScreenLogging() { }
public static ScreenLogging Instance
{
get
{
if(_instance == null)
{
_instance = new ScreenLogging();
}
return _instance;
}
}
private TextBox _target;
public static void SetTarget(TextBox target)
{
Instance._target = target;
}
public static void Write(string content, LoggingLevel warningLevel)
{
//MessageBox.Show(content, warningLevel.ToString());
Instance._target.AppendText(warningLevel.ToString() + ": " + content + "\n");
}
}
}
(Yes there is a reason the screenlogging is separated into a different class, but I really hope I don't have to change that) What can I do to make the calls to this logging class reflect on the UI from within the background worker? Should I change the LogText property to read from an external file or something along those lines? Currently I don't have the background worker implemented, so the logging only shows after the task is completed, but I need to be able to monitor its progress while its running. When I tried putting it into a background worker it errored when it hit a line of code that tried to access the logger.
Since you are trying to update UI from another thread, you must do it in a special way, where threads must be synchronized to transfer data between the them. In other words, it's like the BackgroundWorker needs to do a pause to update the UI. It can be done using the ProgressChanged event of the BackgroundWorker, and the method ReportProgress. Here is a simple example:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// I guess this is how you are using your logger, right?
ScreenLogging.SetTarget(this.txtLogging);
BackgroundWorker worker = new BackgroundWorker();
// Your classic event to do the background work...
worker.DoWork += Worker_DoWork;
// Here you can sender messages to UI.
worker.ProgressChanged += Worker_ProgressChanged;
// Don't forget to turn this property to true.
worker.WorkerReportsProgress = true;
worker.RunWorkerAsync();
}
private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
var worker = sender as BackgroundWorker;
Thread.Sleep(3000);
// ReportProgress sends two values to the ProgressChanged method, for the
// ProgressChangedEventArgs object. The first one is the percentage of the
// work, and the second one can be any object that you need to pass to UI.
// In a simple example, I am passing my log message and just putting
// any random value at progress, since it does not matter here.
worker.ReportProgress(0, "Test!");
}
private void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// Here you get your UserState object, wich is my string message passed on
// with the ReportProgress method above.
var message = e.UserState as string;
// Then you call your log as always. Simple, right?
ScreenLogging.Write(message, LoggingLevel.Info);
}
As your problem seems to not rewrite all your log calls, I will post another way of doing it, by just changing the ScreenLogging.Write method. I hope that works for you, since you will not need to change your calls to Logger.Write method.
public class ScreenLogging
{
private static ScreenLogging _instance;
private ScreenLogging() { }
public static ScreenLogging Instance
{
get
{
if (_instance == null)
{
_instance = new ScreenLogging();
}
return _instance;
}
}
private TextBox _target;
public static void SetTarget(TextBox target)
{
Instance._target = target;
}
public static void Write(string content, LoggingLevel warningLevel)
{
var appendTextAction = new Action(() =>
{
var text = warningLevel.ToString() + ": " + content + "\n";
Instance._target.AppendText(text);
});
// Only the thread that the Dispatcher was created on may access the
// DispatcherObject directly. To access a DispatcherObject from a
// thread other than the thread the DispatcherObject was created on,
// call Invoke and BeginInvoke on the Dispatcher the DispatcherObject
// is associated with.
// You can set the priority to Background, so you guarantee that your
// key operations will be processed first, and the screen updating
// operations will happen only after those operations are done.
Instance._target.Dispatcher.Invoke(appendTextAction,
DispatcherPriority.Background);
}
}

Correct Event handling in C#

this is basically a follow up to a previous question (Triggering an event in c# from c++ and declaring LPCWSTR). I've revised my code based on the answers and comments I have received and I solved the initial issue, which was passing the event to the GpioSetupInterruptPin from a gpio api. I don't have a lot of documentation on the api but what i'm trying to achieve is: have a form with a white label; after pressing a switch, the label turns yellow.
The problem i'm having now is the event seems to trigger as soon as it's created (the "execute" message is passed to the debug dialog and the label turns yellow) but it doesn't do anything when i toggle the switch. I was told in the last question to use WaitForSingleObject but i'm not really sure where to call it and this article only added to my confusion.
public partial class Form1 : Form
{
// P/Invoke CreateEvent and WaitForSingleObject
private void GPIO_Open() //get handle for gpio
private void GPIO_Output() //output pin declaration
private void button1_Click(object sender, EventArgs e)
{
Interrupt_Setup();
}
private void Interrupt_Setup()
{
hGPIO = GPIOapi.GpioOpenHandle(); //returns a handle to the gpio
GIPO_ON = true;
Debug.WriteLine("Driver open \n" + hGPIO);
GPIO_Output(); //set output pins
GPIO_Interrupt(Trigger); //configure interrupt
}
private void GPIO_Interrupt(string trigger)
{
bool ok;
_Main();
//INTERRUPT DECALRATION
ok = GPIOapi.GpioSetupInterruptPin(hGPIO, port6, 4, GPIOapi.INT_TRIGGER_MODE.TRIGGER_MODE_EDGE,
GPIOapi.INT_TRIGGER_POLARITY.TRIGGER_POL_HIGH_RISING, trigger, true);
Thread waitThread=new Thread(WaitForTrigger);
waitThread.Start();
if (!ok)
Debug.WriteLine("NO interrupt");
else
Debug.WriteLine("Interrupt set for:" + port6 + "04" + " at " + hGPIO);
}
public static string Trigger = "InputProcessUpdateHandler";
public static IntPtr handle = CreateEvent(IntPtr.Zero, false, false, Trigger); //used P/Invoke
private static InputProcessor inputProcessor = null;
public Color[] color =
{
Color.Orchid, Color.DarkOrchid, Color.GreenYellow, Color.CornflowerBlue, Color.SteelBlue,Color.Crimson
};
public int i = 0;
public void WaitForTrigger()
{
while(true)
{try
{
if (WaitForSingleObject(handle, 0xFFFFFFFF) == false)
{
BeginInvoke(((System.Action)(() =>label2.BackColor = color[i])));
i++;
if (i > 4)
i = 0;
}
Thread.Sleep(300);
}
catch (Exception e)
{ Debug.WriteLine("exception: " + e); }}
}
}
private void _Main()
{
inputProcessor = new InputProcessor();
ShowToggle showToggle = new ShowToggle(inputProcessor);
inputProcessor.Process(label1);
}
public class ShowToggle
{
private InputProcessor _inputProcessor = null;
public ShowToggle(InputProcessor inputProcessor)
{
_inputProcessor = inputProcessor;
_inputProcessor.updateHandledBy += InputProcessUpdateHandler;
}
private void InputProcessUpdateHandler(Label label)
{
label.BackColor = Color.Yellow;
Debug.Write("execute");
}
}
public class InputProcessor
{
public delegate void InputProcessUpdateHandler(Label label);
public event InputProcessUpdateHandler updateHandledBy = null;
public void Process(Label label)
{
if (updateHandledBy != null)
updateHandledBy(label);
}
}
If anyone could help me with this, I would be very grateful.
*** I got it working but it looks a right mess. Could anyone help me straighten it out?
You code is really confusing to me. I think what you want is something like this. Bear in mind I'm typing this into the SO text editor, so don't expect it to compile and just work - it's a guide. Consider it a step above pseudocode.
public class DeviceInterrupt
{
IntPtr m_gpio;
string m_eventName;
public event EventHandler OnInterrupt;
public DeviceInterrupt(int port)
{
// get a driver handle
m_gpio = GPIO_Open();
// generate some unique event name
m_eventName = "GPIO_evt_" + port;
// wire up the interrupt
GpioSetupInterruptPin(m_gpio, port, m_eventName, ...);
// start a listener
new Thread(EventListenerProc)
{
IsBackground = true,
Name = "gpio listener"
}
.Start();
}
public void Dispose()
{
// TODO: release the handle
}
private void EventListenerProc()
{
// create the event with the name we sent to the driver
var wh = new WaitHandle(false, m_eventName);
while (true)
{
// wait for it to get set by the driver
if (wh.WaitOne(1000))
{
// we have an interrupt
OnInterrupt.Fire(this, EventArgs.Empty);
}
}
}
}
Usage would then be something like this:
var intr = new DeviceInterrupt(4);
intr.OnInterrupt += MyHandler;
....
void MyHandler(object sender, EventArgs a)
{
Debug.WriteLine("Interrupt occurred!");
}
Note
The Compact Framework doesn't support actual named system events, so the named WaitHandle I use in my code above is not a CF-supplied WaitHandle. Instead I'm using the one from the Smart Device Framework. You could also P/Invoke to CreateEvent and WaitForSingleObject yourself.

WPF - Updating Label Content During Processing

Well I've tried several methods of getting this to work, background worker, Dispatcher.Invoke, threading within the called class and nothing seems, to work. The best solution so far is an Extension method which calls the invoke of the control. Also I've tried avoid passing the data for the label through my event classes and simply invoking within my processing code, however this made no difference.
In regards to the background component, I kept getting exceptions saying the background worker was busy, so I instantiated the class several times, however the label only visibly changed once the entire operation had been complete.
I've removed my previous code, here's everything that is relevant, as it seems the issue is difficult to resolve.
Method Being Called
private void TestUris()
{
string text = new TextRange(rtxturis.Document.ContentStart, rtxturis.Document.ContentEnd).Text;
string[] lines = Regex.Split(text.Remove(text.Length - 2), "\r\n");
foreach (string uri in lines)
{
SafeUpdateStatusText(uri);
bool result;
string modUri;
if (!uri.Contains("http://"))
{
modUri = uri;
result = StoreData.LinkUriExists(new Uri("http://" + modUri));
}
else
{
modUri = uri.Substring(7);
result = StoreData.LinkUriExists(new Uri(uri));
}
if (!result)
{
Yahoo yahoo = new Yahoo();
yahoo.Status.Sending += (StatusChange);
uint yahooResult = 0;
yahooResult = yahoo.ReturnLinkCount(modUri);
if (yahooResult > 1000 )
{ results.Add(new ScrapeDetails(Guid.NewGuid(), modUri, 1000, "Will be processed", true)); }
else
{ results.Add(new ScrapeDetails(Guid.NewGuid(), modUri, (int)yahooResult, "Insufficient backlinks", false)); }
}
else
{
results.Add(new ScrapeDetails(Guid.NewGuid(), modUri, 0, "Previously been processed", false));
}
}
foreach (var record in results)
{
dgvresults.Items.Add(record);
}
EnableStartButton();
}
Yahoo Class
public class Yahoo
{
/// <summary>
/// Returns the amount of links each Uri has.
/// </summary>
public uint ReturnLinkCount(string uri)
{
string html;
Status.Update(uri, false); //this is where the status is called
try
{
html = client.DownloadString(string.Format("http://siteexplorer.search.yahoo.com/search?p=http%3A%2F%2F{0}&fr=sfp&bwm=i", uri));
}
catch (WebException ex)
{
ProcessError(ex.ToString());
return 0;
}
return (LinkNumber(html));
}
Status Classes
public class StatusEventArgs : EventArgs
{
private string _message;
private bool _isidle;
public StatusEventArgs(string message, bool isidle)
{
this._message = message;
this._isidle = isidle;
}
public bool IsIdle
{
get { return _isidle; }
}
public string Message
{
get { return _message; }
}
}
public class Status
{
public Status()
{
}
// Declaring an event, with a custom event arguments class
public event EventHandler<StatusEventArgs> Sending;
// Some method to fire the event.
public void Update(string message, bool isIdle)
{
StatusEventArgs msg = new StatusEventArgs(message, isIdle);
OnUpdate(msg);
}
// The method that invokes the event.
protected virtual void OnUpdate(StatusEventArgs e)
{
EventHandler<StatusEventArgs> handler = Sending;
if (handler != null)
{
handler(this, e);
}
}
}
Method That Changes the labels Content
private void StatusChange(object sender, StatusEventArgs e)
{
if(!e.IsIdle)
{
lblstatus.Content = e.Message;
lblstatus.Foreground = StatusColors.Green;
lblstatus.Refresh();
}
else
{
lblstatus.Content = e.Message;
lblstatus.Foreground = StatusColors.Grey;
lblstatus.Refresh();
}
}
The Refresh static method called:
public static class ExtensionMethods
{
private static Action EmptyDelegate = delegate() { };
public static void Refresh(this UIElement uiElement)
{
uiElement.Dispatcher.Invoke(DispatcherPriority.Render , EmptyDelegate);
}
Another EDIT: Staring at my code for a bit longer, I've realised, that the foreach loop will execute really quickly, the operation which takes the time, is
yahooResult = yahoo.ReturnLinkCount(modUri);
Therefore I've declared the status class (which handles the event and invokes the label etc) and subscibed to it. I've gotten better results, although it still feels random, sometimes I see a couple of label updates, and sometimes one even though the exact same URI's are passed, so weird.
I hope there is sth. helpful...
private void button1_Click(object sender, RoutedEventArgs e)
{
ThreadPool.QueueUserWorkItem(o =>
{
int result = 0;
for (int i = 0; i < 9999999; i++)
{
result++;
Dispatcher.BeginInvoke(new Action(() =>
{
this.label1.Content = result;
}));
Thread.Sleep(1);
}
});
}
SOLVED IT YES WOOHOOOOOOOO 3 days of testing, testing, testing.
I decided to start a new project just with the extension method above and a simply for loop to test UI update functionality. I started testing different DispatchPrioraties (tested them all).
Weirdly, I found the highest priorities were the worse, for example using Send didn't update the label at all, Render updated it twice on average. This was the weird behavior I was experiencing as I tried different priorities. I discovered Background:
The enumeration value is 4. Operations are processed after all other non-idle operations are completed.
Now this sounded exactly what I didn't want, as obviously the label should update during processing, hence why I never tried it. I'm guessing that once one of my method has been completed, before the next it called, the UI is updated. I'm find of guessing, but it 100% consistently updates correctly on two separate operations.
Thanks all.
Well this is going to sound stupid but you could just reference the forms namespace, and then you can do this
using System.Windows.Forms;
mylabel = "Start";
Application.doEvents();
myLabel = "update"
Application.doEvents();
now the problem using this would be you are using wpf but you can still reference forms and use this namespace. The other issue is what ever is in the que would execute directly to the ui. However this is the most simplistic way of doing label updates i could think of.
would it be easier/better to add the status info as a property on this object, and have it just fire property change notifications?
that way the label text (or whatever) could be bound to the property instead of having the async work try to update a label?
or add a method like this to update status if you have to update it?
void SafeUpdateStatusText(string text)
{
// update status text on event thread if necessary
Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate
{
lblstatus.Content = text;
}, null);
}
otherwise, i don't think we have enough details to help yet....
I hope this helps:
private delegate void UpdateLabelDelegate(DependencyProperty dp, object value);
public void UpdateLabelContent(Label label, string newContent)
{
Dispatcher.Invoke(new UpdateLabelDelegate(label.SetValue), DispatcherPriority.Background, ContentProperty, newContent);
}
Usage:
while (true)
{
UpdateLabelContent(this.lblStatus, "Next random number: " + new Random().Next());
Thread.Sleep(1000);
}

Categories

Resources