Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#任务异步等待智能卡-UI线程被阻止_C#_Multithreading_Task Parallel Library_Async Await_Smartcard - Fatal编程技术网

C#任务异步等待智能卡-UI线程被阻止

C#任务异步等待智能卡-UI线程被阻止,c#,multithreading,task-parallel-library,async-await,smartcard,C#,Multithreading,Task Parallel Library,Async Await,Smartcard,我是C#的新手,我正在尝试对WinsForm GUI使用task async Wait。我已经阅读了很多关于它的教程,但它们都以不同的方式执行任务。有些任务使用函数,而另一些任务只是将代码放入其中执行。有些人使用Task.Run()或只是等待。此外,我看到的所有示例都是UI类中包含的函数。我正在尝试运行UI中的类中的函数。我现在真的很困惑,不知道什么是对的/错的 我正在尝试使用SpringCardAPI/PC/SC库将文件写入EEPROM。我将文件解析为数据包并将其写入智能卡。我还想更新状态标签

我是C#的新手,我正在尝试对WinsForm GUI使用task async Wait。我已经阅读了很多关于它的教程,但它们都以不同的方式执行任务。有些任务使用函数,而另一些任务只是将代码放入其中执行。有些人使用Task.Run()或只是等待。此外,我看到的所有示例都是UI类中包含的函数。我正在尝试运行UI中的类中的函数。我现在真的很困惑,不知道什么是对的/错的

我正在尝试使用SpringCardAPI/PC/SC库将文件写入EEPROM。我将文件解析为数据包并将其写入智能卡。我还想更新状态标签和进度条。很多事情都会出错。我在智能卡中设置了标志,现在我只是循环运行一段时间,直到它读取到某个标志,如果程序一直在等待标志,这显然会使程序暂停

我想我只是对如何设置感到困惑。帮助我试过使用任务。这是到目前为止我的代码

/* Initialize open file dialog */
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Multiselect = false;
            ofd.Filter = "BIN Files (.bin)|*.bin|HEX Files (.hex)|*.hex";
            ofd.InitialDirectory = "C:";
            ofd.Title = "Select File";

            //Check open file dialog result
            if (ofd.ShowDialog() != DialogResult.OK)
            {
                if (shade != null)
                {
                    shade.Dispose();
                    shade = null;
                }
                return;
            }

            //progform.Show();
            Progress<string> progress = new Progress<string>();
            file = new ATAC_File(ofd.FileName);

            try
            {
                cardchannel.DisconnectReset();
                Task upgrade = upgradeASYNC();

                if(cardchannel.Connect())
                {
                    await upgrade;
                }
                else
                {
                    add_log_text("Connection to the card failed");

                    MessageBox.Show("Failed to connect to the card in the reader : please check that you don't have another application running in background that tries to work with the smartcards in the same time");
                    if (shade != null)
                    {
                        shade.Dispose();
                        shade = null;
                    }

                    cardchannel = null;
                }
        }


    private async Task upgradeASYNC()
        {
            int i = 0;
            int totalpackets = 0;

            add_log_text("Parsing file into packets.");
            totalpackets = file.parseFile();

            /*progress.Report(new MyTaskProgressReport
            {
                CurrentProgressAmount = i,
                TotalProgressAmount = totalpackets,
                CurrentProgressMessage = "Sending upgrade file..."
            });*/

            ST_EEPROMM24LR64ER chip = new ST_EEPROMM24LR64ER(this, cardchannel, file, EEPROM.DONOTHING);

            bool writefile = chip.WriteFileASYNC();
            if(writefile)
            {
                add_log_text("WRITE FILE OK.");
            }
            else
            {
                add_log_text("WRITE FILE BAD.");
            }

        }
/*初始化打开文件对话框*/
OpenFileDialog ofd=新建OpenFileDialog();
ofd.Multiselect=false;
ofd.Filter=“BIN文件(.BIN)|*.BIN |十六进制文件(.HEX)|*.HEX”;
ofd.InitialDirectory=“C:”;
ofd.Title=“选择文件”;
//检查打开文件对话框结果
if(ofd.ShowDialog()!=DialogResult.OK)
{
if(shade!=null)
{
阴暗处处理();
shade=null;
}
回来
}
//progform.Show();
进度=新的进度();
文件=新的ATAC_文件(ofd.FileName);
尝试
{
cardchannel.DisconnectReset();
任务升级=升级异步();
if(cardchannel.Connect())
{
等待升级;
}
其他的
{
添加日志文本(“连接到卡失败”);
MessageBox.Show(“无法连接到读卡器中的卡:请检查您没有另一个在后台运行的应用程序试图同时使用智能卡”);
if(shade!=null)
{
阴暗处处理();
shade=null;
}
cardchannel=null;
}
}
专用异步任务upgradeASYNC()
{
int i=0;
int-totalpackets=0;
添加日志文本(“将文件解析为数据包”);
totalpackets=file.parseFile();
/*进度报告(新的MyTaskProgressReport)
{
CurrentProgressAmount=i,
TotalProgressAmount=totalpackets,
CurrentProgressMessage=“正在发送升级文件…”
});*/
ST_-EEPROMM24LR64ER芯片=新的ST_-EEPROMM24LR64ER(此、卡通道、文件、EEPROM.DONOTHING);
bool writefile=chip.WriteFileASYNC();
if(writefile)
{
添加日志文本(“写入文件确定”);
}
其他的
{
添加日志文本(“写入文件错误”);
}
}
在文件类中:

public int parseFile()
        {
            FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
            BinaryReader br = new BinaryReader(fs);
            FileInfo finfo = new FileInfo(filename);

            int readbytecount = 0;
            int packetcount = 0;
            int numofbytesleft = 0;
            byte[] hash = new byte[4];
            byte[] packetinfo = new byte[4];
            byte[] filechunk = null;

            /* Read file until all file bytes read */
            while (size_int > readbytecount)
            {
                //Initialize packet array
                filechunk = new byte[MAXDATASIZE];

                //read into byte array of max write size
                if (packetcount < numoffullpackets)
                {
                    //Initialize packet info array
                    packetinfo[0] = (byte)((size_int + 1) % 0x0100); //packetcountlo
                    packetinfo[1] = (byte)((size_int + 1) / 0x0100); //packetcounthi
                    packetinfo[2] = (byte)((packetcount + 1) / 0x0100); //packetcounthi
                    packetinfo[3] = (byte)((packetcount + 1) % 0x0100); //packetcountlo

                    //read bytes from file into packet array
                    bytesread = br.Read(filechunk, 0, MAXDATASIZE);

                    //add number of bytes read to readbytecount
                    readbytecount += bytesread;
                }
                //read EOF into byte array of size smaller than max write size
                else if (packetcount == numoffullpackets)
                {
                    //find out how many bytes left to read
                    numofbytesleft = size_int - (MAXDATASIZE * numoffullpackets);

                    //Initialize packet info array
                    packetinfo[0] = (byte)((size_int + 1) / 0x0100); //packetcounthi
                    packetinfo[1] = (byte)((size_int + 1) % 0x0100); //packetcountlo
                    packetinfo[2] = (byte)((packetcount + 1) / 0x0100); //packetcounthi
                    packetinfo[3] = (byte)((packetcount + 1) % 0x0100); //packetcountlo

                    //Initialize array and add byte padding, MAXWRITESIZE-4 because the other 4 bytes will be added when we append the CRC
                    //filechunk = new byte[numofbytesleft];
                    for (int j = 0; j < numofbytesleft; j++)
                    {
                        //read byte from file
                        filechunk[j] = br.ReadByte();

                        //add number of bytes read to readbytecount
                        readbytecount++;
                    }

                    for (int j = numofbytesleft; j < MAXDATASIZE; j++)
                    {
                        filechunk[j] = 0xFF;
                    }
                }
                else
                {
                    MessageBox.Show("ERROR");
                }

                //calculate crc32 on byte array
                int i = 0;
                foreach (byte b in crc32.ComputeHash(filechunk))
                {
                    hash[i++] = b;
                }

                //Append hash to filechunk to create new byte array named chunk
                byte[] chunk = new byte[MAXWRITESIZE];
                Buffer.BlockCopy(packetinfo, 0, chunk, 0, packetinfo.Length);
                Buffer.BlockCopy(filechunk, 0, chunk, packetinfo.Length, filechunk.Length);
                Buffer.BlockCopy(hash, 0, chunk, (packetinfo.Length + filechunk.Length), hash.Length);

                //Add chunk to byte array list
                packetcount++;
                PacketBYTE.Add(chunk);
            }

            parseCMD();

            return PacketBYTE.Count;
        }
public int parseFile()
{
FileStream fs=newfilestream(文件名,FileMode.Open,FileAccess.Read);
BinaryReader br=新的BinaryReader(fs);
FileInfo finfo=新的FileInfo(文件名);
int readbytecount=0;
int packetcount=0;
int numobytesleft=0;
字节[]散列=新字节[4];
字节[]packetinfo=新字节[4];
byte[]filechunk=null;
/*读取文件,直到读取所有文件字节*/
while(size\u int>readbytecount)
{
//初始化数据包数组
filechunk=新字节[MAXDATASIZE];
//读入最大写入大小的字节数组
if(包数public bool WriteFileASYNC()
    {
        int blocknum = ATAC_CONSTANTS.RFBN_RFstartwrite;
        byte[] response = null;
        CAPDU[] EEPROMcmd = null;
        int packetCount = 0;

        log("ATTEMPT: Read response funct flag.");
            do
            {
                StopRF();
                Thread.SpinWait(100);
                StartRF();
                log("ATTEMPT: Write function flag.");
                while (!WriteFlag(ATAC_CONSTANTS.RFBN_functflag, EEPROM.UPLOADAPP)) ;
            } while (ReadFunctFlag(ATAC_CONSTANTS.RFBN_responseflag, 0) != EEPROM.UPLOADAPP);  

            for (int EEPROMcount = 0; EEPROMcount < file.CmdBYTE.Count; EEPROMcount++)
            {
                string temp = "ATTEMPT: Write EEPROM #" + EEPROMcount.ToString();
                log(temp);
                EEPROMcmd = file.CmdBYTE[EEPROMcount];

                while (EEPROMcmd[blocknum] != null)
                {
                    if (blocknum % 32 == 0)
                    {
                        string tempp = "ATTEMPT: Write packet #" + packetCount.ToString();
                        log("ATTEMPT: Write packet #");
                        packetCount++;
                    }

                    do
                    {
                        response = WriteBinaryASYNC(EEPROMcmd[blocknum]);
                    } while (response == null);

                    blocknum++;
                }

                log("ATTEMPT: Write packet flag.");
                while (!WriteFlag(ATAC_CONSTANTS.RFBN_packetflag, ATAC_CONSTANTS.RFflag)) ;

                log("ATTEMPT: Write packet flag.");
                do
                {
                    StopRF();
                    Thread.SpinWait(300);
                    StartRF();

                } while (!ReadFlag(ATAC_CONSTANTS.RFBN_packetresponseflag, ((blocknum/32) - 1)*(EEPROMcount+1)));

                blocknum = ATAC_CONSTANTS.RFBN_RFstartwrite;
            }

            return true;
        }
Task upgrade = upgradeASYNC();
 await upgrade;
private async Task upgradeASYNC()