C#后台工作者进程问题 [英] c# Background worker process problem

查看:55
本文介绍了C#后台工作者进程问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,下面是我使用的Windows窗体代码.

Hi guys following is the windows form code I am using.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.IO;
using System.Deployment;
using System.Threading;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Reflection;
using System.Windows.Forms;
namespace FORMBROADCASTER
{
    public partial class Form1 : Form
    {        
        BackGroundProcess obj = new BackGroundProcess();
       
        public Form1()
        {
            InitializeComponent();            
        }
       
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {               
                this.obj.backgroundWorker1.RunWorkerAsync();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            //backgroundWorker1.WorkerSupportsCancellation = true;
            try
            {
                if (obj.backgroundWorker1.IsBusy)
                {
                    obj.backgroundWorker1.CancelAsync();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message,"Error");
            }
        }                
    }
}



现在从上述表单中,我正在创建以下类的对象



Now from the above form I am creating the Object of the following Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.ComponentModel;
using System.Reflection;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace FORMBROADCASTER
{
    class BackGroundProcess
    {
        public BackgroundWorker backgroundWorker1 ;
        public static long iRecPack = 0;
        public static long i7201 = 0;
        public static long i7202 = 0;
        public static long i7208 = 0;
        public static long i6541 = 0;
        public static long i7207 = 0;
        public static long iOther = 0;
        int n;
        public static long iSentPack = 0;
        public static market_Indices[] mIndices;
        public static UdpClient sendBrod = new UdpClient("192.168.201.24", 7864);
        public static UdpClient sendBrod1 = new UdpClient("192.168.201.24", 7865);
        UdpClient peer ;
        IPAddress multicastaddress ;
        IPEndPoint ep ;
        public BackGroundProcess()
        {
            backgroundWorker1 = new BackgroundWorker();
            backgroundWorker1.WorkerSupportsCancellation = true;
            backgroundWorker1.WorkerReportsProgress = true;
            backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
            peer = new UdpClient(34074);
            multicastaddress = IPAddress.Parse("233.1.2.5");
            ep = null;
        }
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            //Form1 form12 = new Form1();
            
            peer.JoinMulticastGroup(multicastaddress);
            //Thread oThread = new Thread(new ThreadStart(VISIONNSEMARKETWATCH.Program.processByte()));
            int j = 0;
            Stopwatch stopwatch = new Stopwatch();
            //TextWriter tw = new StreamWriter("c:\\data.txt");
            //if (!backgroundWorker1.IsBusy)
            //{
                while (!backgroundWorker1.CancellationPending)
                {
                    try
                    {
                        //System.Windows.Forms.Application.DoEvents();
                        ep = new IPEndPoint(IPAddress.Any, 34074);
                        stopwatch.Start();
                        byte[] data = peer.Receive(ref ep);
                        stopwatch.Stop();
                        MWProperties[] mwproc = new MWProperties[2];
                        int i = processByte(ref data, ref mwproc);
                        j++;
                    }                    
                    finally
                    {
                        //System.GC.Collect();
                    }
                    stopwatch.Reset();                    
                }
            //}
            //else
            //{
            //    //MessageBox.Show("You can't start another thread");
            //}
            peer = null;
            //tw.Close();
        }
        public static void TwidleBytes(Byte[] b, int fStart, int fSize)
        {
            Array.Reverse(b, fStart - 1, fSize);
        }
        public int processByte(ref byte[] byt, ref MWProperties[] newprop)
        {
            #region "Variable Declaration"
            byte[] Ibyt = new byte[byt.Length];
            int iLineCount = 0;
            String _Detail;
            String _Summary = "";//"Token,MarketType,FillPrice,FillVolume,OpenInterest,DayHiOI,DayLoOI"; 
            IntPtr p;
            Byte[] bytDecompressed;
            BcastCmpPacket Bcp = new BcastCmpPacket();
            BcastPackData Bpd = new BcastPackData();
            #endregion
            try
            {
                //Mapping the BroadCast Data to Packet Structure According Para 3.6 of Document & fetching the cPackData
                Array.Copy(byt, Ibyt, byt.Length);
                TwidleBytes(byt, 1, 2);
                TwidleBytes(byt, 3, 2);
                p = Marshal.AllocHGlobal(Marshal.SizeOf(Bpd));
                Marshal.Copy(byt, 0, p, byt.Length);
                Bpd = (BcastPackData)Marshal.PtrToStructure(p, Bpd.GetType());
                Marshal.FreeHGlobal(p);
                byt = Bpd.cPackData;
                TwidleBytes(byt, 1, 2);

                // Mapping the cPackData to COMPRESSION_BROADCAST_DATA 
                Bpd = new BcastPackData();
                p = Marshal.AllocHGlobal(Marshal.SizeOf(Bcp));
                Marshal.Copy(byt, 0, p, byt.Length);
                Bcp = (BcastCmpPacket)Marshal.PtrToStructure(p, Bcp.GetType());
                //Console.WriteLine(Bcp.iCompLen);
                // If in COMPRESSION_BROADCAST_DATA CompressionLen is not equle to 0
                if (Bcp.iCompLen > 0)
                {
                    //Steps to decompree the Data
                    Console.WriteLine(p.ToString());
                    Marshal.FreeHGlobal(p);
                    bytDecompressed = new Byte[Bcp.iCompLen];
                    byt = new Byte[Bcp.iCompLen];
                    Array.Copy(Bcp.cCompData, byt, Bcp.iCompLen);
                    int length = LatestLZO.lzo11_decomp(ref byt, out bytDecompressed);
                    //bytDecompressed = new LZOCompressor().Decompress(byt);
                    //Fetching the Message Header
                    Bcp = new BcastCmpPacket();
                    byt = new Byte[56];
                    Array.Copy(bytDecompressed, 8, byt, 0, 56);
                    //Fethcing the Transaction Code from Message_Header
                    my_Message_Header Mh = new my_Message_Header();
                    TwidleBytes(byt, 9, 4);
                    TwidleBytes(byt, 37, 2);
                    TwidleBytes(byt, 39, 2);
                    p = Marshal.AllocHGlobal(Marshal.SizeOf(Mh));
                    Marshal.Copy(byt, 0, p, byt.Length);
                    Mh = (my_Message_Header)Marshal.PtrToStructure(p, Mh.GetType());
                    Marshal.FreeHGlobal(p);
                    int StartIndex = 48;
                    int i = Int16.Parse(bytDecompressed[49].ToString());
                    Bcast_Header Bh = new Bcast_Header();
                    if (Mh.TransactionCode == 7208)
                    {
                        i7208++;
                        newprop = new MWProperties[i];

                        for (int n = 0; n < i; n++)
                        {
                            //double Value = 0.0;
                            //_Detail = "";
                            byt = new Byte[212];
                            Array.Copy(bytDecompressed, 50 + (n * 212), byt, 0, 212);
                            sendBrod.Send(byt, byt.Length);
                            //byt = null;                           
                        }
                        return 7208;
                    }
                }
                else
                {
                    bytDecompressed = new byte[506];
                    Array.Copy(Bcp.cCompData, bytDecompressed, bytDecompressed.Length);
                    Bcp = new BcastCmpPacket();
                    byt = new Byte[56];
                    Array.Copy(bytDecompressed, 8, byt, 0, 56);
                    my_Message_Header Mh = new my_Message_Header();
                    Marshal.FreeHGlobal(p);
                    TwidleBytes(byt, 9, 4);
                    TwidleBytes(byt, 37, 2);
                    TwidleBytes(byt, 39, 2);
                    p = Marshal.AllocHGlobal(Marshal.SizeOf(Mh));
                    Marshal.Copy(byt, 0, p, byt.Length);
                    Mh = (my_Message_Header)Marshal.PtrToStructure(p, Mh.GetType());
                    Marshal.FreeHGlobal(p);
                    int StartIndex = 48;
                    int i = Int16.Parse(bytDecompressed[49].ToString());
                    Bcast_Header Bh = new Bcast_Header();
                    if (Mh.TransactionCode == 7207)
                    {
                        i7207++;
                        mIndices = new market_Indices[i];
                        for (int m = 0; m < i; m++)
                        {
                            mIndices[m] = new market_Indices();
                            Ticker_7207 indices = new Ticker_7207();
                            byte[] indbyte = new byte[72];
                            Array.Copy(bytDecompressed, 50 + (m * 72), indbyte, 0, 72);
                            //Array.Reverse(indbyte, 21, indbyte.Length - 21);
                            sendBrod1.Send(indbyte, indbyte.Length);
                            //indbyte = null;                            
                        }
                        return 7207;
                    }
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show("Exception is : " + ex.Message);
                //sendBrod.Close();
                //sendBrod = null;
            }
            finally
            {
                //System.GC.Collect();
            }
            return 0;
        }


现在,我希望当我单击表单中的按钮时,backgroundWorker进程应该启动.然后在


Now I want that when I click the button in form, backgroundWorker process should start. then Inside

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)

我正在从多播IP地址接收广播数据包.


然后我调用函数

I am receiving the broadcast packets from the multicast Ip address.


Then I make a call to the function

public int processByte(ref byte[] byt, ref MWProperties[] newprop)

该字节并将其作为广播数据包发送.

但是,当我单击按钮1要启动时,我的应用程序运行不正常.运行一段时间后,有时会挂起.有时会给我错误
试图读取或写入受保护的内存.这通常表明其他内存已损坏."

所有这些事情大多发生在运行"模式下,即当我按ctr + f5时. &在调试模式下,应用程序会完全运行

which processes this bytes and sends it as broadcast packet.

But my application is not behaving properly some time when I click button1 it want start. Sometime it hangs after running some times. Some time it gives me the error
"Attempted to read or write protected memory. This is often an indication that other memory is corrupt."

And all this things happens mostly in Run mode means when I press ctr + f5. & In debug mode application runs perfactly

推荐答案

在调试模式下,应用程序会完全运行"
我敢打赌不会.

您在那里有很多地方正在使用try块,这些块要么没有捕获,要么被丢弃.如果您忽略了例外情况,怎么知道您的应用程序正在运行?

处理渔获物-至少记录错误.您可能会发现,其中一个例外稍后会导致严重问题.
"In debug mode application runs perfactly"
I bet it doesn''t.

You have a number of places there where you are using try blocks with either no catch, or discarded catches. How do you know you app is working, if you are ignoring the exceptions?

Handle the catches - at least log the errors. You may well find that one of the exceptions is causing the serious problem later on.


hi kkprocks123,

您的榜样对我来说是很大的资源.成功解压缩后,我尝试按照my.Message_Header(按doc中可用的结构进行映射),该结构的大小为40字节.所以我将my_Message_Header的代码更改为56到40,并将字节位置更改为
每个文档都可用my_Message_Header,这样做我没有得到有意义的数据.我得到了不在文档中的交易代码.你能帮我吗?

av_m222@Yahoo.com
hi kkprocks123,

Your example is a great resourse for me. After successful decompression I tried to map my_Message_Header, as per structure avaiable in doc which is 40 byte in size. so I changed your code where my_Message_Header is 56 to 40 and position of bytes to be twidled for
my_Message_Header as per doc available.Doing so I am not getting meaningful data.I got Transaction Code which is not in doc. Could you help me here?

av_m222@Yahoo.com


这篇关于C#后台工作者进程问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆