Why is my GUI freezing?

I am new to the TPL world and I made this code:

    var myItems = myWpfDataGrid.SelectedItems;

    this.Dispatcher.BeginInvoke(new Action(() =>
    {
        var scheduler = new LimitedConcurrencyLevelTaskScheduler(5);
        TaskFactory factory = new TaskFactory(scheduler);

        foreach (MyItem item in myItems)
        {
            Task myTask = factory.StartNew(() =>

            DoLoooongWork(item)                   

                ).ContinueWith((t) =>
                {
                    Debug.WriteLine(t.Exception.Message);
                    if (t.Exception.InnerException != null)
                    {
                        Debug.WriteLine(t.Exception.InnerException.Message);
                    }
                },
                TaskContinuationOptions.OnlyOnFaulted);
        }
    }), null);            

The only access to gui is " var myItems = myWpfDataGrid.SelectedItems; " and this is read-only! The function "DoLoooongWork ()" has access to serial ports, etc. This is a shared SDK function that does not have access to a graphical interface. I know that "Dispatcher.BeginInvoke" is a bit redundant, but I donโ€™t know what I can do or what I am doing wrong. The only reason for this code is to free the GUI when DoLoooongWork () is executed, but the GUI is frozen!

What is wrong with this code?

change

Thanks to @Euphoric help, I found a problem similar to this post: COM Interop hang freezes the entire COM system. How to cancel a COM call

+4
2

, -, , , . , . , , , .

+1

, DoLoooongWork . ThreadWithAffinityContext , , :

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);
    }
}

ThreadWithAffinityContext.

[UPDATE] , DoLoooongWork :

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

"zkemkeeper" , . -, Connect_Net , , :

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);
        // ...
    }
}

. , , - .

+3

Source: https://habr.com/ru/post/1524338/


All Articles