开发者

Thread.Start not working

开发者 https://www.devze.com 2023-04-10 09:01 出处:网络
I am using the functions of the following class to invoke a messagebox. I am using thread.Start method to show the messagebox. The problem is it is not reaching to the respective functionwhen thread.S

I am using the functions of the following class to invoke a messagebox. I am using thread.Start method to show the messagebox. The problem is it is not reaching to the respective function when thread.Start is called. Am i missing anything?

class MessageManager
{
  string _message;
  public MessageManager(string message)
  {
    _message = message;
  }

  public void ShowBigMessage()
  {
    Thread thread = new Thread(DisplayBigMessage);
    thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA
    thread.Start();

    // thread.Join(); 
  }

  public void ShowNormalMessage()
  {
    Thread thread = new Thread(DisplayNormalMessage);
    thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA
    thread.Start();
    //thread.Join(); 
  }

  private void DisplayBigMessage()
  {
    BigAppMessage appMessage = new BigAppMessage(_message);
    appMessage.Show();
  }

  private void DisplayNormalMessage()
  {
    AppMessage appMessage = new AppMessage(_message);
    appMessage.ShowDialog();
  }
}

This is called inside a thread/delegate as below. I added this cod开发者_StackOverflowe into my program becuase it was raising

The calling thread must be STA, because many UI components require this.

exception before

MessageManager message = new MessageManager("This is a test message.");

                    message.ShowBigMessage();





  public partial class BigAppMessage : Window
    {
        public BigAppMessage(String message)
        {
            InitializeComponent();
            myControl.setMessage(message); // mycontrol is just user control with a                   
                                           //label on it
        }       

    }


The Show() method requires a message loop. Fix:

  private void DisplayBigMessage()
  {
    Application.Run(new BigAppMessage(_message));
  }

There's already a message loop built into the ShowDialog() method. Using a thread to just display a window has no advantages, only problems.


In visual studio go to Debug->Exceptions and check the "thrown" box next to CLR exceptions. this will tell you where your problem is. Probably its a cross thread issue since you would ordinarily only interact with the UI on the UI thread.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号