C#线程安全套接字混乱

时间:2019-05-16 15:01:30

标签: c# multithreading thread-safety

我有一个我认为是线程安全的问题。

我有两台打印机,一台装有小标签,另一台装有大标签。我想通过套接字将1个打印作业发送到每个打印机。

我尝试对第一个请求(大标签)进行线程处理/后台处理,因为它可能需要很长时间才能完成。

99%的时间脚本正常工作。大小标签从各自的打印机中发出。

但是,时不时地,大标签和小标签都被发送到同一台打印机!不管是大还是小。

我认为这与线程安全性有关,但是我发现很难跟踪和了解正在发生的事情。我曾尝试添加一个锁并在使用后关闭套接字,但是无论如何,问题仍然存在。

我试图将我的代码减少到最低限度,但是我知道这篇文章仍然非常繁琐。任何建议将不胜感激。

// stores the printer info
class PrinterBench
{
    public PrinterBench(string sArg_PostageLabelIP, string sArg_SmallLabelIP)
    {
        PostageLabelIP = sArg_PostageLabelIP;
        SmallLabelIP = sArg_SmallLabelIP;
    }
    public string PostageLabelIP;
    public string SmallLabelIP;
}

// main entry point
class HomeController{

    PrintController oPrintController;
    List<string> lsLabelResults = new List<string>("label result");
    PrinterBench pbBench        = new PrinterBench("192.168.2.20","192.168.2.21");

    void Process(){

        oPrintController = new PrintController(this);

        if(GetLabel()){
            // should always come out of the big printer (runs in background)
            oPrintController.PrintBySocketThreaded(lsLabelResults, pbBench.PostageLabelIP);
            // should always come out of the small printer
            oPrintController.PrintWarningLabel();
        }
    }
}


class PrintController{

    HomeController oHC;
    public EndPoint ep { get; set; }
    public Socket sock { get; set; }
    public NetworkStream ns { get; set; }

    private static Dictionary<string, Socket> lSocks = new Dictionary<string, Socket>();

    private BackgroundWorker _backgroundWorker;
    static readonly object locker = new object();
    double dProgress;
    bool bPrintSuccess = true;

    public PrintController(HomeController oArg_HC)
    {
        oHC = oArg_HC;
    }

    public bool InitSocks()
    {
        // Ensure the IP's / endpoints of users printers are assigned
        if (!lSocks.ContainsKey(oHC.pbBench.PostageLabelIP))
        {
            lSocks.Add(oHC.pbBench.PostageLabelIP, null);
        }
        if (!lSocks.ContainsKey(oHC.pbBench.SmallLabelIP))
        {
            lSocks.Add(oHC.pbBench.SmallLabelIP, null);
        }

        // attempt to create a connection to each socket
        foreach (string sKey in lSocks.Keys.ToList())
        {
            if (lSocks[sKey] == null || !lSocks[sKey].Connected )
            {
                ep = new IPEndPoint(IPAddress.Parse(sKey), 9100);
                lSocks[sKey] = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                lSocks[sKey].Connect(ep);
            }
        }
        return true;
    }


    public bool PrintBySocketThreaded(List<string> lsToPrint, string sIP)
    {
        // open both the sockets
        InitSocks();

        bBatchPrintSuccess = false;
        _backgroundWorker = new BackgroundWorker();

        _backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork);
        _backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;
        _backgroundWorker.WorkerReportsProgress = true;
        _backgroundWorker.WorkerSupportsCancellation = true;

        object[] parameters = new object[] { lsToPrint, sIP, lSocks };

        _backgroundWorker.RunWorkerAsync(parameters);
        return true;
    }


    // On worker thread, send to print!
    public void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        object[] parameters = e.Argument as object[];

        double dProgressChunks = (100 / ((List<string>)parameters[0]).Count);
        int iPos = 1;

        Dictionary<string, Socket> dctSocks = (Dictionary<string, Socket>)parameters[2];

        foreach (string sLabel in (List<string>)parameters[0] )
        {
            bool bPrinted = false;

            // thread lock print by socket to ensure its not accessed twice
            lock (locker)
            {
                // get relevant socket from main thread
                bPrinted = PrintBySocket(sLabel, (string)parameters[1], dctSocks[(string)parameters[1]]);
            }

            iPos++;
        }

        while (!((BackgroundWorker)sender).CancellationPending)
        {
            ((BackgroundWorker)sender).CancelAsync();
            ((BackgroundWorker)sender).Dispose();
            //Thread.Sleep(500);
        }
        return;
    }


    // Back on the 'UI' thread so we can update the progress bar (have access to main thread data)!
    private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        if (e.Error != null) MessageBox.Show(e.Error.Message);
        if (bPrintSuccess) oHC.WriteLog("Printing Complete");

        bBatchPrintSuccess = true;

        ((BackgroundWorker)sender).CancelAsync();
        ((BackgroundWorker)sender).Dispose();
    }

    /// sends to printer via socket
    public bool PrintBySocket(string sArg_ToPrint, string sIP, Socket sock = null)
    {
        Socket sTmpSock = sock;

        if (sTmpSock == null)
        { 
            InitSocks();

            if (!lSocks.ContainsKey(sIP)){
                throw new Exception("Sock not init");
            }else{
                sTmpSock = lSocks[sIP];
            }
        }

        using (ns = new NetworkStream(sTmpSock))
        {
            byte[] toSend = Encoding.ASCII.GetBytes(sEOL + sArg_ToPrint);
            ns.BeginWrite(toSend, 0, toSend.Length, OnWriteComplete, null);
            ns.Flush();
        }
        return true;
    }


    public bool PrintWarningLabel()
    {
        string sOut = sEOL + "N" + sEOL;
        sOut += "LL411" + sEOL;
        sOut += "R40,0" + sEOL;
        sOut += "S5" + sEOL;
        sOut += "D15" + sEOL;
        sOut += "A0,0,0,4,4,3,N,\"!!!!!!!!!!!!!!!!!!!!!!!\"" + sEOL;
        sOut += "A0,150,0,4,3,3,N,\"WARNING MESSAGE TO PRINT\"" + sEOL;
        sOut += "A0,280,0,4,4,3,N,\"!!!!!!!!!!!!!!!!!!!!!!!\"" + sEOL;
        sOut += "P1";
        sOut += sEOL;

        if (PrintBySocket(sOut, oHC.pbBench.SmallLabelIP))
        {
            oHC.WriteLog("WARNING LABEL PRINTED");
            return true;
        }
        return false;
    }
}

1 个答案:

答案 0 :(得分:1)

您在public NetworkStream ns { get; set; } 中有此字段:

    using (ns = new NetworkStream(sTmpSock))
    {
        byte[] toSend = Encoding.ASCII.GetBytes(sEOL + sArg_ToPrint);
        ns.BeginWrite(toSend, 0, toSend.Length, OnWriteComplete, null);
        ns.Flush();
    }

仅在这里使用:

ns

如果两个线程同时执行此操作,则当另一个要写入时,一个线程可以将NetworkStream更改为另一个ns

由于using (var ns = new NetworkStream(sTmpSock)) 已在此处使用和放置,因此似乎没有任何理由将其声明为字段,这意味着多个线程可以覆盖它。而是删除该字段并将代码更改为此:

NetworkStream

然后,执行此操作的多个线程将创建自己的{{1}}作为局部变量,而不是争用一个。

我还要检查所有其他字段,看看它们是否需要为字段,或者是否可以将它们声明为局部变量。

无意共享状态对多线程代码不利。它的行为将完全符合您的描述。它会起作用,它会起作用,然后再起作用,然后就不起作用了,并且在您希望看到问题时重现该问题几乎是不可能的。