Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
504 views
in Technique[技术] by (71.8m points)

c# - Why is Task.Wait() causing application to freeze

When I call BuildCustomer.StartTask, I then call a method WriteToDatabase. Inside WriteToDatabase, I want to send a status back to the MainForm to write the status to the GUI. When the code reaches that point, my application freezes up and gives no error. I did find out that if I remove task.Wait(), it stops freezing and works. But I think I want the wait in because my BuildCustomer takes a bit of time and writes a lot of updates (including more updates from Common class) to the GUI. Can someone tell me what is wrong or what I should be doing differently? This is a .Net 4 project so I cannot use async, which I've seen other answers for.

public partial class MainForm : Window
{
    public MainForm()
    {
        Common.SendMessage += UpdateStatus;
    }

    private void Button_Click(object sender, EventArgs e)
    {
        BuildCustomer.StartTask();
    }

    private void UpdateStatus(string message)
    {
        Dispatcher.Invoke(new Action(() =>
        {
            StatusTextBox.Text = message;
        }));
    }
}

public class BuildCustomer
{
    public static void StartTask()
    {
        var action = new Action<object>(BuildCustomer);

        var task = new Task(() => action(buildDetails));

        task.Start();

        task.Wait();
    }

    private void BuildCustomerDetails(object buildDetails)
    {
        Common.WriteToDatabase();
    }
}

public class Common
{
    public delegate void MessageLogDelegate(string message);

    public static event MessageLogDelegate SendMessage;

    public static void WriteToDatabase()
    {
        SendMessage("Some status message to write back to the GUI");
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have a deadlock. The StartTask waits on task.Wait() to complete but this occurs (is called on) on the calling thread which is the main UI thread.

The Task being waited eventually reaches UpdateStatus which calls an Invoke on the UI thread as well but this thread is currently waiting on task.Wait() (so it is blocking which results in the UI thread not being available indefinitely).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...