Why is my GUI freezing?

前端 未结 2 1606
梦谈多话
梦谈多话 2021-01-20 04:04

I\'m new in TPL world, and I did that code:

    var myItems = myWpfDataGrid.SelectedItems;

    this.Dispatcher.BeginInvoke(new Action(() =>
    {
                


        
相关标签:
2条回答
  • 2021-01-20 04:22

    I had a hunch that something working with serial port would try to use application's event loop to do it's work. So it actually bypasses the whole dispatcher and thread system and blocks the application. I'm not experienced in this field so I don't know how to solve it, but this is different question.

    0 讨论(0)
  • 2021-01-20 04:24

    I presume some objects inside DoLoooongWork require thread affinity and message pumping. Try my ThreadWithAffinityContext and see if helps, use it like this:

    private async void Button_Click(object sender, EventArgs e)
    {
        try 
        {           
            using (var staThread = new Noseratio.ThreadAffinity.ThreadWithAffinityContext(
                 staThread: true, pumpMessages: true))
            {
                foreach (MyItem item in myItems)
                {
                    await staThread.Run(() =>
                    {
                        DoLoooongWork(item);
                    }, CancellationToken.None);
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
    

    More info about ThreadWithAffinityContext.

    [UPDATE] You mentioned in the comments that the code inside DoLoooongWork looks like this:

    zkemkeeper.CZKEM axCZKEM1 = new zkemkeeper.CZKEM(); 
    axCZKEM1.Connect_Net(ip, port);
    

    I never heard of "zkemkeeper" before, but I did a brief search and found this question. Apparently, Connect_Net only establishes the connection and starts a session, while the whole communication logic happens asynchronously via some events, as that question suggests:

    bIsConnected = axCZKEM1.Connect_Net("192.168.0.77", Convert.ToInt32("4370"));
    if (bIsConnected == true)
    {
        iMachineNumber = 1;
        if (axCZKEM1.RegEvent(iMachineNumber, 65535))
        {
            this.axCZKEM1.OnFinger += new kemkeeper._IZKEMEvents_OnFingerEventHandler(axCZKEM1_OnFinger);
            this.axCZKEM1.OnVerify += new zkemkeeper._IZKEMEvents_OnVerifyEventHandler(axCZKEM1_OnVerify);
            // ...
        }
    }
    

    That would be a whole different story. Leave a comment if that's the case and you're still interested in some solution.

    0 讨论(0)
提交回复
热议问题