What is causing my UI Thread to be blocked?

Ice Drake

I am completely lost in what is really causing the problem. So rather trying to explain the problem, I might as well as get straight to the code with the problem. Here is the layout of my program:

    private void connection_OnMessage(object sender, agsXMPP.protocol.client.Message msg)
    {     
        if (!string.IsNullOrEmpty(msg.Body) && ((msg.XDelay != null && msg.XDelay.Stamp.Date == DateTime.Today) || msg.XDelay == null))
        {
            agsXMPP.Jid JID = new Jid(msg.From.Bare);

            int rowIndex = chatLog.Rows.Add();
            chatLog.Rows[rowIndex].Cells["chatNameColumn"].Value = JID.User;
            chatLog.Rows[rowIndex].Cells["chatMessageColumn"].Value = msg.Body;

            //Begin line of the problem
            if (IncomingMessage != null)
                IncomingMessage(this, JID.User, msg.Body);
            //End of the problem
        }
    }

The above code snippet is of class A. After starting up the program, this class makes the connection to the server. Right after being connected, this code snippet is rapidly fired about 20 times, once per line of message. (There are already about 20 lines of message in the chat log.) Since only one message makes it through the if condition, the lines commented with the problem is only run once. Those lines fire the code snippet below of class B.

(Around the time class A is firing, I have another class like A that fires the similar event to be handled by class B the same way, which will be handled by class C.)

    private void newSource_IncomingMessage(IChatSource sender, string user, string message)
    {
        UpdatedMessageEventHandler temp = UpdatedMessage;
        if (temp != null)
            temp(sender, user, message);
    }

The above code snippet of class B fires the code snippet below of class C.

    private void chatManager_UpdatedMessage(IChatSource source, string user, string message)
    {
        if (!source.Muted)
        {
            updateMessage(source, user, message);
        }            
    }

    delegate void UpdateMessageCallback(IChatSource source, string user, string message);

    private void updateMessage(IChatSource source, string user, string message)
    {
        if (allDataGridView.InvokeRequired)
        {
            UpdateMessageCallback d = new UpdateMessageCallback(updateMessage);
            Invoke(d, new object[] { source, user, message });
        }
        else
        {
            int row = allDataGridView.Rows.Add();
            allDataGridView.Rows[row].DefaultCellStyle.ForeColor = source.TextColor;
            allDataGridView.Rows[row].Cells["NameColumn"].Value = user;
            allDataGridView.Rows[row].Cells["MessageColumn"].Value = message;

            if (!MenuItem.Checked)
            {
                MenuItem.Checked = true;
                Show();
            }
        }
    }

Here is what I tried to do to fix the problem, but the code is removed already:

  1. I tried adding lock to certain codes.
  2. I tried to put the certain codes on a separate thread and have them run.

Here is what happened:

  1. When I run the program, the UI thread seems to be blocked. In other words, class C doesn't get painted. Sometimes, the form doesn't even appear.
  2. A few times, it complaint about a strange error "An error occurred invoking the method. The destination thread no longer exists."
  3. If I commented out the problem lines, everything work fine, but here is the strange part. If I create a timer object in class A and have it fired the event the same way, it works fine.
  4. While line stepping in debug mode, I sometimes got it work fine, but majority of the time, it fails.
  5. For a few times, I run into InvalidOperationException with the message, "Control accessed from a thread other than the thread it was created on." even though I did make it thread safe.

In conclusion, I don't know what is causing the UI thread to be blocked. Any pointer or what I might do wrong?

Jeroen van Langen

The problem is that you're calling methods crossthreading. This can lead to deadlocks.

You could solve this, adding the messages on a concurrent queue and on a timer (gui thread) checking the queue and adding the messages to controls.

This is not a complete solution, but a method to prevent crossthread method invoking

Like: (PSEUDO) (wrote online on the site)

// dataholder
public class ChatMsg
{
    public string User {get;set;}
    public string Message {get;set;}
}

// message store
private List<ChatMsg> _messages = new List<ChatMsg>();
// timer
private Timer _timer;

// callback for you chatapi?? (like you wrote)
private void newSource_IncomingMessage(IChatSource sender, string user, string message)
{
    UpdatedMessageEventHandler temp = UpdatedMessage;

    // lock the store
    lock(_messages)
        _messages.Add(new ChatMsg { User = user, Message = message });
}

// constructor
public Form1()
{
    // create the check timer.
    _timer = new Timer();
    _timer.Interval = 100;
    _timer.Tick += Timer_Tick;
    _timer.Start();
}

// timer method
private void Timer_Tick(object sender, EventArgs e)
{
    // copy of the queue
    ChatMsg[] msgs;

    // lock the store and 'move' the messages
    lock(_messages)
    {
        msgs = _messages.ToArray();
        _messages.Clear();
    }

    if(msgs.Length == 0)
        return;

    // add them to the controls
    foreach(var msg in msgs)
    {
        // add the message to the gui controls... (copied from your question)
        int row = allDataGridView.Rows.Add();
        allDataGridView.Rows[row].DefaultCellStyle.ForeColor = source.TextColor;
        allDataGridView.Rows[row].Cells["NameColumn"].Value = user;
        allDataGridView.Rows[row].Cells["MessageColumn"].Value = message;
   }
}

Something like that..

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Why the UI thread is getting blocked?

From Dev

Android UI Thread blocked in new Activity

From Dev

WPF UI Thread blocked with large collection

From Dev

Xamarin Async and Await: UI thread is getting blocked

From Dev

What is causing the artifacts in my raytracer?

From Dev

What is causing error in my code

From Dev

Thread Posting messages to Main UI Thread are blocked/removed

From Dev

Multiple Realm transactions causing UI thread to freeze

From Dev

What does Thread.interrupt() do if the thread isn't blocked?

From Dev

What is causing self to be undefined in my AppDelegate?

From Dev

What is causing the issue with my WIX installed application?

From Dev

What is causing my border to not extend to the top and the bottom?

From Dev

What is causing my spacebar to randomly stop working?

From Dev

What is causing my application to fail to start?

From Dev

What is causing my jQuery functions not run?

From Dev

What is causing this issue with my array...?

From Dev

IllegalArgumentException: UnknownBitmapConfiguration what is causing my game to crash?

From Dev

What is causing my border to not extend to the top and the bottom?

From Dev

What is causing my kafka log segments to be deleted?

From Dev

What is causing a Stack Overflow in my code?

From Dev

What element is causing my accordion to have spaces?

From Dev

What is causing my spacebar to randomly stop working?

From Dev

Why is a thread blocking my JavaFX UI Thread?

From Dev

Multi-thread UI causing WPF application to stop working

From Dev

What is executed in the NOT UI THREAD in a IntentService?

From Dev

What's causing my stackoverflowerror in my maze solver?

From Dev

What is causing my files to save to My Document instead of the specified path?

From Dev

What is causing my files to save to My Document instead of the specified path?

From Dev

Thread blocked after await

Related Related

  1. 1

    Why the UI thread is getting blocked?

  2. 2

    Android UI Thread blocked in new Activity

  3. 3

    WPF UI Thread blocked with large collection

  4. 4

    Xamarin Async and Await: UI thread is getting blocked

  5. 5

    What is causing the artifacts in my raytracer?

  6. 6

    What is causing error in my code

  7. 7

    Thread Posting messages to Main UI Thread are blocked/removed

  8. 8

    Multiple Realm transactions causing UI thread to freeze

  9. 9

    What does Thread.interrupt() do if the thread isn't blocked?

  10. 10

    What is causing self to be undefined in my AppDelegate?

  11. 11

    What is causing the issue with my WIX installed application?

  12. 12

    What is causing my border to not extend to the top and the bottom?

  13. 13

    What is causing my spacebar to randomly stop working?

  14. 14

    What is causing my application to fail to start?

  15. 15

    What is causing my jQuery functions not run?

  16. 16

    What is causing this issue with my array...?

  17. 17

    IllegalArgumentException: UnknownBitmapConfiguration what is causing my game to crash?

  18. 18

    What is causing my border to not extend to the top and the bottom?

  19. 19

    What is causing my kafka log segments to be deleted?

  20. 20

    What is causing a Stack Overflow in my code?

  21. 21

    What element is causing my accordion to have spaces?

  22. 22

    What is causing my spacebar to randomly stop working?

  23. 23

    Why is a thread blocking my JavaFX UI Thread?

  24. 24

    Multi-thread UI causing WPF application to stop working

  25. 25

    What is executed in the NOT UI THREAD in a IntentService?

  26. 26

    What's causing my stackoverflowerror in my maze solver?

  27. 27

    What is causing my files to save to My Document instead of the specified path?

  28. 28

    What is causing my files to save to My Document instead of the specified path?

  29. 29

    Thread blocked after await

HotTag

Archive