/// <summary> /// 显示进度信息 /// </summary> /// <param name="owner"></param> /// <param name="message"></param> /// <param name="minimum"></param> /// <param name="maximum"></param> /// <param name="IsIndeterminate">如果ProgressBar 显示实际值,则为 false;如果 ProgressBar 显示一般进度,则为 true。</param> /// <returns></returns> public static fmProgress Show(string message, int minimum, int maximum, bool IsIndeterminate) { SplashManualResetEvent.Reset(); ThreadParam param = new ThreadParam(); param.Message = message; param.Maximum = maximum; param.Minimum = minimum; param.IsIndeterminate = IsIndeterminate; param.Value = 0; Thread th = new Thread(new ParameterizedThreadStart(ShowProgressWindow)); th.IsBackground = true; th.SetApartmentState(ApartmentState.STA); th.Start(param); SplashManualResetEvent.WaitOne(); return window; }
protected override void OnStart(string[] args) { _ThreadList = new List<Thread>(); _gpiList = new List<GPIDevice>(); _inovonicsList = new List<InovonticsDevice>(); string inovIp = Settings.Default.InovonicsIp; string ipCCure = Settings.Default.RelayIp; int colPort = Settings.Default.RelayPort; ThreadParam tp = new ThreadParam(); tp.ipCCure = ipCCure; tp.ipInovonics = inovIp; tp.portCCure = colPort.ToString(); _thread = new Thread(new ParameterizedThreadStart(thread_worker)); _ThreadList.Add(_thread); _thread.Start(tp); }
private void buttonStart_Click(object sender, EventArgs e) { UpdateListBox("Starting Relay Service..."); _ThreadList=new List<Thread>(); _gpiList = new List<GPIDevice>(); _inovonicsList=new List<InovonticsDevice>(); string colIP =Settings.Default.InovonicsIp; string ipCCure = Settings.Default.RelayIp; string colPort = Settings.Default.RelayPort; ThreadParam tp = new ThreadParam(); tp.ipCCure = ipCCure; tp.ipInovonics = colIP; tp.portCCure = colPort; _thread = new Thread(new ParameterizedThreadStart(thread_worker)); _ThreadList.Add(_thread); _thread.Start(tp); }
int SendMail(string subject, string body, int how) { IntPtr vsWindow; IVsUIShell shell = VsAppShell.Current.GetGlobalService<IVsUIShell>(typeof(SVsUIShell)); shell.GetDialogOwnerHwnd(out vsWindow); MapiMessage msg = new MapiMessage(); msg.subject = subject; msg.noteText = body; msg.recips = GetRecipients(out msg.recipCount); msg.files = GetAttachments(out msg.fileCount); ThreadParam p = new ThreadParam() { Message = msg, VsWindow = vsWindow, MapiFlags = how }; bool success = false; Thread t = null; try { _completed.Reset(); t = new Thread(ThreadProc, 8192); t.Start(p); success = _completed.Wait(5000); } catch (Exception) { } if (!success) { if (t != null) { t.Abort(); } } Cleanup(ref msg); return _result; }
// User callback function (C# thread) private void CallbackThread(object tParam) { try { // Get Mutex lock for Marshal.Copy() this.MarshalCopyMutex.WaitOne(); // Parameter for delegate ThreadParam Param = new ThreadParam(); Param.eventID = ((ThreadParam)tParam).eventID; Param.eventData = ((ThreadParam)tParam).eventData; Param.userData = ((ThreadParam)tParam).userData; EVENTDATA ev = new EVENTDATA(); FPD_ALARM fa = new FPD_ALARM(); Byte[] imagePtr = null; // Thumbnail image collected // Full image collected if ((TETD_EVENT_CALLBACK_ENUM.TETD_EVENT_EXP_IMG_THUMB == (TETD_EVENT_CALLBACK_ENUM)Param.eventID) || (TETD_EVENT_CALLBACK_ENUM.TETD_EVENT_EXP_IMG_FULL == (TETD_EVENT_CALLBACK_ENUM)Param.eventID)) { ev = (EVENTDATA)Marshal.PtrToStructure(Param.eventData, typeof(EVENTDATA)); imagePtr = new Byte[ev.myEventData[2]]; Marshal.Copy((IntPtr)ev.myEventData[1], imagePtr, 0, imagePtr.Length); } // Normal event if ((TETD_EVENT_CALLBACK_ENUM.TETD_EVENT_FPD_ALARM != (TETD_EVENT_CALLBACK_ENUM)Param.eventID) && (TETD_EVENT_CALLBACK_ENUM.TETD_EVENT_FPD_REBOOT_ERROR != (TETD_EVENT_CALLBACK_ENUM)Param.eventID)) { ev = (EVENTDATA)Marshal.PtrToStructure(Param.eventData, typeof(EVENTDATA)); } // Alarm from FPD else { fa = (FPD_ALARM)Marshal.PtrToStructure(Param.eventData, typeof(FPD_ALARM)); } // Delegate for other thread this.BeginInvoke(this.CallbackFromFPD_Delegate, Param.eventID, Param.eventData, Param.userData, ev, fa, imagePtr); // Release Mutex lock for Marshal.Copy() this.MarshalCopyMutex.ReleaseMutex(); } catch { } }
// User callback function (C++ thread) private void CallbackFromFPD(Int32 eventID, IntPtr eventData, IntPtr userData) { try { // Parameter from C++ thread to C# thread ThreadParam Param = new ThreadParam(); Param.eventID = eventID; Param.eventData = eventData; Param.userData = userData; // Start C# thread Thread CSthread = new Thread(new ParameterizedThreadStart(CallbackThread)); CSthread.Start(Param); // Wait for Marshal.Copy() CSthread.Join(); } catch { } // return from User callback function }
private void bw1_DoWork(object sender, DoWorkEventArgs e) { String[] files = (String[])e.Argument; int realsize = (parseOnly.Checked && numBlocks.Value > 0) ? (int)numBlocks.Value : files.Length; int div = realsize / 3; ThreadParam puno = new ThreadParam(); puno.files = new string[div]; Array.Copy(files, 0, puno.files, 0, div); puno.num = 1; ThreadParam pdue = new ThreadParam(); pdue.files = new string[div]; Array.Copy(files, div, pdue.files, 0, div); pdue.num = 2; ThreadParam ptre = new ThreadParam(); ptre.files = new string[realsize - 2 * div]; Array.Copy(files, 2 * div, ptre.files, 0, realsize - 2 * div); ptre.num = 3; Thread t1 = new Thread(new ParameterizedThreadStart(MyThreadCalc)); Thread t2 = new Thread(new ParameterizedThreadStart(MyThreadCalc)); Thread t3 = new Thread(new ParameterizedThreadStart(MyThreadCalc)); t1.Start(puno); t2.Start(pdue); t3.Start(ptre); t1.Join(); t2.Join(); t3.Join(); }
static void LoadProblems(object paramsInfo) { ThreadParam threadParam = (ThreadParam)paramsInfo; QuestionManager.LoadQuestion(threadParam.Start, threadParam.End); }
private void AsyncExecute(object obj) { ThreadParam para = (ThreadParam)obj; try { cmdProcess = new System.Diagnostics.Process(); //如果使用cmd Arguments前面要加/c 如果使用adb Arguments可以直接复制 cmdProcess.StartInfo.FileName = para.exe; // 命令 cmdProcess.StartInfo.Arguments = para.exe == "cmd.exe" ? "/c " + para.cmd : para.cmd; // 参数 cmdProcess.StartInfo.CreateNoWindow = true; // 不创建新窗口 cmdProcess.StartInfo.UseShellExecute = false; cmdProcess.StartInfo.RedirectStandardInput = true; // 重定向输入 cmdProcess.StartInfo.RedirectStandardOutput = true; // 重定向标准输出 cmdProcess.StartInfo.RedirectStandardError = true; // 重定向错误输出 //CmdProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; cmdProcess.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(OutputDataReceived); cmdProcess.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(ErrorDataReceived); ////在Unity发布后Exited不会调用,原因未知 //cmdProcess.EnableRaisingEvents = true; // 启用Exited事件 //cmdProcess.Exited += new EventHandler(CmdProcess_Exited); // 注册进程结束事件 cmdProcess.Start(); cmdProcess.BeginOutputReadLine(); cmdProcess.BeginErrorReadLine(); if (callback != null) { PushToMainThread(ExecuteState.StartSuccess); } } catch (Exception ex) { Debug.LogWarning(ex); if (callback != null) { PushToMainThread(ExecuteState.StartFailed); } } //等待执行完毕 cmdProcess.WaitForExit(); try { if (isExit) { exitCode = cmdProcess.ExitCode; } } catch (Exception ex) { Debug.LogWarning(ex); } if (callback != null) { PushToMainThread(ExecuteState.Finished); } }
private static async Task ProcessEvents(ThreadParam param, IFullEvent[] events) { var delayed = events.Select(x => x.Event as IDelayedMessage).ToArray(); Logger.Write(LogLevel.Debug, () => $"Processing {delayed.Count()} bulk events from stream [{events.First().Descriptor.StreamId}] bucket [{events.First().Descriptor.Bucket}] entity [{events.First().Descriptor.EntityType}]"); var contextBag = new ContextBag(); // Hack to get all the delayed messages to bulk invoker without NSB deserializing and processing each one contextBag.Set(Defaults.BulkHeader, delayed); // Run bulk process on this thread using (var tokenSource = CancellationTokenSource.CreateLinkedTokenSource(param.Token)) { var success = false; var retry = 0; var messageId = Guid.NewGuid().ToString(); do { var transportTransaction = new TransportTransaction(); // Need to supply EnclosedMessageTypes to trick NSB pipeline into processing our fake message var headers = new Dictionary <string, string>() { [Headers.EnclosedMessageTypes] = typeof(BulkMessage).AssemblyQualifiedName, [Headers.MessageIntent] = MessageIntentEnum.Send.ToString(), [Headers.MessageId] = messageId, [Defaults.BulkHeader] = delayed.Count().ToString(), }; try { // If canceled, this will throw the number of time immediate retry requires to send the message to the error queue param.Token.ThrowIfCancellationRequested(); // Don't re-use the event id for the message id var messageContext = new NServiceBus.Transport.MessageContext(messageId, headers, Marker, transportTransaction, tokenSource, contextBag); await Bus.OnMessage(messageContext).ConfigureAwait(false);//param.Token); tokenSource.Token.ThrowIfCancellationRequested(); Logger.Write(LogLevel.Debug, () => $"Scheduling acknowledge of {delayed.Count()} bulk events"); DelayedHandled.Increment(delayed.Count()); await param.Consumer.Acknowledge(events).ConfigureAwait(false); success = true; } catch (ObjectDisposedException) { // NSB transport has been disconnected throw new OperationCanceledException(); } catch (Exception e) { // Don't retry a cancelation if (tokenSource.IsCancellationRequested) { throw; } DelayedErrors.Mark($"{e.GetType().Name} {e.Message}"); if ((retry % param.MaxRetry) == 0) { Logger.Warn($"So far, we've received {retry} errors while running {delayed.Count()} bulk events from stream [{events.First().Descriptor.StreamId}] bucket [{events.First().Descriptor.Bucket}] entity [{events.First().Descriptor.EntityType}]", e); } // Don't burn cpu in case of non-transient errors await Task.Delay((retry / 5) * 200, param.Token).ConfigureAwait(false); } retry++; // Keep retrying forever but print warn messages once MaxRetry exceeded } while (!success); } }
protected static void Loop(object param) { byte[] recvBuffer = new byte[40960]; List <byte[]> tmpSendBytes = new List <byte[]>(); const int POLL_WAIT_MS = 25; ThreadParam threadParam = param as ThreadParam; while (!threadParam.isExit && 0 == threadParam.errno && ClientSocketState.Connected == threadParam.state) { const int TIMEOUT_ERRNO = 10060; try { if (threadParam.socket.Poll(POLL_WAIT_MS, System.Net.Sockets.SelectMode.SelectRead)) { // receive int recvLen = threadParam.socket.Receive(recvBuffer, 0, recvBuffer.Length, SocketFlags.None); if (recvLen <= 0) { threadParam.errno = 2; threadParam.errmsg = "remote close socket"; } else { byte[] bytes = new byte[recvLen]; Array.Copy(recvBuffer, bytes, recvLen); threadParam.mtx.WaitOne(); threadParam.recvBytes.Add(bytes); threadParam.mtx.ReleaseMutex(); } } } catch (Exception e) { SocketException se = e as SocketException; if (null == se || TIMEOUT_ERRNO != se.ErrorCode) { threadParam.errno = 1; threadParam.errmsg = e.Message; continue; } } try { // send threadParam.mtx.WaitOne(); tmpSendBytes.AddRange(threadParam.sendBytes); threadParam.sendBytes.Clear(); threadParam.mtx.ReleaseMutex(); if (threadParam.socket.Poll(POLL_WAIT_MS, System.Net.Sockets.SelectMode.SelectWrite)) { int i = 0; int lastSendLen = 0; for (; i < tmpSendBytes.Count; ++i) { byte[] currBytes = tmpSendBytes[i]; lastSendLen = threadParam.socket.Send(currBytes); if (lastSendLen < currBytes.Length) { break; } } if (i >= tmpSendBytes.Count) { tmpSendBytes.Clear(); } else { byte[] lastBytes = tmpSendBytes[i]; byte[] lastLeftBytes = new byte[lastBytes.Length - lastSendLen]; Array.Copy(lastBytes, lastSendLen, lastLeftBytes, 0, lastLeftBytes.Length); if (i == tmpSendBytes.Count - 1) { tmpSendBytes.Clear(); } else { tmpSendBytes = tmpSendBytes.GetRange(i + 1, tmpSendBytes.Count); } tmpSendBytes.Insert(0, lastLeftBytes); } } } catch (Exception e) { SocketException se = e as SocketException; if (null == se || TIMEOUT_ERRNO != se.ErrorCode) { threadParam.errno = 1; threadParam.errmsg = e.Message; continue; } } } }
void ExecuteADCommand(string ctrName, string ip, string exePath) { if (!_threadList.ContainsKey(ctrName)) { Thread thread = new Thread(new ParameterizedThreadStart((object param) => { ThreadParam arg = param as ThreadParam; int width = arg.UnitType.ModuleWidth * arg.UnitType.ModulePixelWidth; int height = arg.UnitType.ModuleHeight * arg.UnitType.ModulePixelHeight; int modulePixelWidth = arg.UnitType.ModulePixelWidth; int modulePixelHeight = arg.UnitType.ModulePixelHeight; bool isReset = arg.ResetData; string fileRead = ""; string fileWrite = ""; OperationResult operationResult = _baseCommunication.OpenDevice(arg.IP, 0, 8001); if (!operationResult.Status) { //设备打开失败 Log(arg.IP, MultiLanguage.GetNames(Name, "OpenDeviceFailed")); return; } else { Log(arg.IP, MultiLanguage.GetNames(Name, "OpenDeviceSuccess")); } int devNum = operationResult.DeviceNumber; if (!_devIP.ContainsKey(devNum)) { _devIP.Add(devNum, arg.IP); } try { LEDCmdCordination cmdAddr = new LEDCmdCordination() { groupPortX = 1, groupPortY = 1, cabinetAddressX = 255, cabinetAddressY = 255, moduleAddressX = 1, moduleAddressY = 1 }; operationResult = _baseCommunication.LampBoardReadTimecode(devNum, cmdAddr); if (!operationResult.Status) { //读取时间码失败 Log(ip, MultiLanguage.GetNames(Name, "ReadTimeCodeFailed")); operationResult.Status = false; SetCommandStatus(arg.IP, false); return; } string timeCode = operationResult.strData; string tmpPath = System.IO.Path.GetTempPath(); tmpPath = System.IO.Path.Combine(tmpPath, timeCode); if (Directory.Exists(tmpPath)) { Directory.Delete(tmpPath, true); } Thread.Sleep(500); Directory.CreateDirectory(tmpPath); while (!Directory.Exists(tmpPath)) { Directory.CreateDirectory(tmpPath); } DialogResult dlgResult = DialogResult.Yes; string outFile = ""; if (arg.ReadCalFrom == 0 && CheckIsExistLocalCalibrationData(arg.UnitType, operationResult.DeviceNumber, timeCode, System.IO.Path.Combine(arg.WorkPath, "Read"), out outFile)) { //从箱体读取数据 //本地已经存在时间码对应的校正数据 dlgResult = MessageBoxEx(MultiLanguage.GetNames(Name, "IsLoadLocalCalibrationDataFile"), MessageBoxButtons.YesNoCancel); if (dlgResult == DialogResult.Cancel) { Log(ip, MultiLanguage.GetNames(Name, "CanceledByUser")); operationResult.Status = false; SetCommandStatus(arg.IP, false); return; } if (dlgResult == DialogResult.Yes) { arg.LocalCalDataPath = tmpPath; string fileName = System.IO.Path.GetFileName(outFile); string tmpFile = System.IO.Path.Combine(tmpPath, fileName); File.Copy(outFile, tmpFile, true); arg.ReadCalFrom = 1; } } string tmpRead = System.IO.Path.Combine(tmpPath, "read1"); if (arg.ReadCalFrom == 0) { //从箱体读取数据 Log(ip, MultiLanguage.GetNames(Name, "ReadCalibrationDataFromCabinet")); Thread.Sleep(200); operationResult = ReadCalibrationDataFromCabinet(operationResult.DeviceNumber, arg.IP, arg.UnitType, tmpRead); } else { //从文件夹读取数据 Log(ip, MultiLanguage.GetNames(Name, "ReadCalibrationDataFromFolder")); operationResult = ReadADCalibrationDataFormFolder(arg.UnitType, arg.LocaCalFileType, devNum, arg.IP, arg.LocalCalDataPath); if (!operationResult.Status) { //读取校正数据失败 Log(arg.IP, operationResult.Message); SetCommandStatus(arg.IP, false); return; } tmpRead = operationResult.strData; } if (!operationResult.Status) { //读取校正数据失败 Log(arg.IP, MultiLanguage.GetNames(Name, "ReadCalibrationFailed")); SetCommandStatus(arg.IP, false); return; } else { Log(arg.IP, MultiLanguage.GetNames(Name, "ReadCalibrationSuccess")); } string tmpSdat = System.IO.Path.Combine(tmpPath, "read1_translate_sdat.sdat"); operationResult = TranslateCalibrationDataToSdat(tmpRead, width, height, tmpSdat); if (!operationResult.Status) { Log(arg.IP, operationResult.Message); SetCommandStatus(ip, false); return; } //保存原始数据 string extName = GetCalibrationTrueExt(tmpRead, width, height); fileRead = System.IO.Path.Combine(arg.WorkPath, "Read/read" + timeCode + extName); File.Copy(tmpRead, fileRead, true); //TODO:修改 CalibrationProcess process = new CalibrationProcess(); EnumDataType dataType = process.GetDataType(width, height, tmpRead); fileWrite = System.IO.Path.Combine(arg.WorkPath, "Read/write" + timeCode + "." + extName); operationResult = ChangeCalibrationData(tmpSdat, fileWrite, width, height, modulePixelWidth, modulePixelHeight, arg.StartGray, arg.SeamData, dataType); if (!operationResult.Status) { //读取时间码失败 Log(ip, operationResult.Message); SetCommandStatus(ip, false); return; } //TODO:写入 Log(ip, MultiLanguage.GetNames(Name, "WriteCalibrationData")); //operationResult = _baseCommunication.MainBoardUploadCalibrationFile(devNum, cmdAddr, uType.ModulePixelWidth, uType.ModulePixelHeight, fileWrite); Point[] changedModuleAddress = GetChangedModuleAddress(arg.SeamData, isReset); operationResult = WriteModuleFiles(ip, devNum, timeCode, arg.UnitType, fileWrite, changedModuleAddress, tmpPath); if (!operationResult.Status) { //写入校正数据失败 Log(arg.IP, operationResult.Message); SetCommandStatus(arg.IP, false); return; } else { Log(arg.IP, MultiLanguage.GetNames(Name, "WriteCalibrationDataSuccess")); SetCommandStatus(arg.IP, true); File.Copy(fileWrite, fileRead, true); } } finally { _baseCommunication.CloseDevice(devNum); _devIP.Remove(devNum); _threadList.Remove(ctrName); } })); thread.IsBackground = true; _threadList.Add(ctrName, thread); ThreadParam threadParam = new ThreadParam() { ControlName = ctrName, IP = ip, SeamData = ViewForm.SeamData.Clone() as SeamItemData[, ], StartGray = (byte)_interfaceData.StarGray, UnitType = GetCabinetType(), WorkPath = exePath, LocalCalDataPath = txtDataLocation.Text, LocaCalFileType = cbDataType.SelectedIndex, ReadCalFrom = cbdataPos.SelectedIndex, ResetData = ckReset.Checked }; //_threadList[ctrName].Start(new object[] { ctrName, ip, ViewForm.SeamData.Clone(), _interfaceData.Background, GetCabinetType(), exePath, txtDataLocation.Text, cbdataPos.SelectedIndex, cbDataType.SelectedIndex }); _threadList[ctrName].Start(threadParam); } }
private void SDFileUploadThread(object obj) { IPAddress localaddr = IPAddress.Parse("0.0.0.0"); TcpListener tcpserver = new TcpListener(localaddr, 0); tcpserver.Start(); IPEndPoint localep = (IPEndPoint)tcpserver.LocalEndpoint; WorkProcessHandler h = new WorkProcessHandler(UploadFileProcess); ThreadParam ap = (ThreadParam)obj; DeviceListener.Device d = deviceListener.Find(ap.id); if (d == null) { return; } string fname = System.IO.Path.GetFileName(ap.filename); //int ret = deviceListener.FilePlayStart(d, "0.0.0.0", localep.Port, ap.streamtype, ap.volume, null); int ret = deviceListener.SDCardUploadFile(d, "0.0.0.0", localep.Port, fname); if (ret != 0) { return; } TcpClient tc = null; try { long starttime = DateTime.Now.Ticks; while ((DateTime.Now.Ticks - starttime) < 3000 * 10000)//3000ms { if (tcpserver.Pending()) { tc = tcpserver.AcceptTcpClient(); break; } } if (tc != null) { FileStream fs = File.OpenRead(ap.filename); if (fs != null) { bool eof = false; long writebytes = 0; byte[] fbs = new byte[1024]; NetworkStream tcs = tc.GetStream(); while (!eof) { if (tcs.CanWrite) { int readbytes = fs.Read(fbs, 0, fbs.Length); tcs.Write(fbs, 0, readbytes); writebytes += readbytes; if (readbytes < fbs.Length) { eof = true; } int process = (int)(100 * writebytes / fs.Length); this.BeginInvoke(h, d, ap.filename, false, process); } } } tc.Close(); } this.BeginInvoke(h, d, ap.filename, true, 0); dataThread = null; } catch (ThreadAbortException abortException) { //this.BeginInvoke(h, ap.filename, true, 0); if (tc != null) { tc.Close(); } dataThread = null; } }
public void DownLoad(object param) { ThreadParam tParam = param as ThreadParam; ManualResetEvent close = tParam.close; AutoResetEvent Wait = tParam.waitfor; try { while (bContinue) { Wait.WaitOne(); HttpRequest req = null; string strURI = null; while (bContinue) { req = null; strURI = null; foreach (KeyValuePair <string, HttpRequest> each in TaskMap) { if (each.Value.Status != TaskStatus.Normal) { continue; } if (req == null) { req = each.Value; } if (strURI == null) { strURI = each.Key; } } if (req == null) { continue; } Socket sClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP); //http1.1 download start string strHost = ""; string strPort = ""; string strRelativePath = ""; if (!ParseURI(strURI, ref strHost, ref strPort, ref strRelativePath)) { req.error = "404"; if (req.OnReceivedData != null && !req.bDone) { req.OnReceivedData(ref req); } break; } else { EndPoint server = new IPEndPoint(IPAddress.Parse(strHost), System.Convert.ToInt32(strPort)); try { connectDone.Reset(); sClient.BeginConnect(server, new AsyncCallback(ConnectCallback), sClient); connectDone.WaitOne(2000, false); if (!sClient.Connected) { Log.WriteError("connect time out"); req.Status = TaskStatus.Error; continue; } } catch { req.error = "connect failed"; if (req.OnReceivedData != null && !req.bDone) { req.OnReceivedData(ref req); } req.Status = TaskStatus.Error; continue; } if (!sClient.Connected) { req.error = "connect failed"; req.OnReceivedData(ref req); req.Status = TaskStatus.Error; continue; } string strSend = string.Format(strHttpVer, strRelativePath, strHost, strPort, req.cbstart); Log.WriteError("send packet:" + strSend); byte[] bySend = System.Text.Encoding.UTF8.GetBytes(string.Format(strHttpVer, strRelativePath, strHost, strPort, req.cbstart)); sClient.Send(bySend); int nByteRecved = 0; int nNewLine = 0; //recv http head MemoryStream ms = new MemoryStream(); byte[] byteRecved = new byte[1]; while (true) { if (!bContinue) { break; } try { nByteRecved = sClient.Receive(byteRecved, 1, 0); } catch (Exception exp) { break; } if (nByteRecved <= 0) { break; } ms.Write(byteRecved, 0, 1); if (byteRecved[0] == '\n') { nNewLine++; if (System.Text.Encoding.UTF8.GetString(ms.GetBuffer()).Contains("\r\n\r\n")) { break; } } } if (!sClient.Connected || !bContinue) { req.error = "recv interrupt"; if (req.OnReceivedData != null && !req.bDone) { req.OnReceivedData(ref req); } req.Status = TaskStatus.Error; continue; } nByteRecved = 0; string strHead = System.Text.Encoding.UTF8.GetString(ms.GetBuffer()); Log.WriteError("http recv:" + strHead); string strHeadLower = strHead.ToLower(); //check http1.1 return code int nReturnCode = 0; long nContentLength = 0; string[] strResponse = new string[nNewLine]; char[] split = { '\n' }; strResponse = strHeadLower.Split(split); for (int i = 0; i < strResponse.Length; ++i) { if (strResponse[i].Contains("http/")) { string strStatus = strResponse[i]; nReturnCode = System.Convert.ToInt32(strStatus.Substring(9, 3)); Log.WriteError("http result:" + nReturnCode.ToString()); } else if (strResponse[i].Contains("content-length:")) { string strLength = strResponse[i]; string[] strSplit = strLength.Split(new char[] { ' ' }, 2); nContentLength = System.Convert.ToInt64(strSplit[1]); if (req.cbstart == 0) { req.totalBytes = nContentLength; if (req.OnReceivedData != null && !req.bDone) { req.OnReceivedData(ref req); } } } else if (strResponse[i].Contains("tranfer-encoding:chunked")) { Log.WriteError("error !!! can not read chunked data"); req.error = "can not read chunked data"; req.Status = TaskStatus.Error; } if (nReturnCode != 0 && nContentLength != 0) { break; } } ms.Close(); ms = null; if (!string.IsNullOrEmpty(req.error) || req.Status != TaskStatus.Normal) { if (req.OnReceivedData != null) { req.OnReceivedData(ref req); } continue; } if (nReturnCode != 206 && nReturnCode != 200) { req.error = nReturnCode.ToString(); if (req.OnReceivedData != null && !req.bDone) { req.OnReceivedData(ref req); } req.Status = TaskStatus.Error; sClient.Close(); continue; } if (req.fs == null) { req.fs = File.Open(req.strLocalPath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite); if (req.cbstart != 0) { req.fs.Seek(req.cbstart, SeekOrigin.Begin); } } //calc kbps //total recved / total time => kbps long nTotalRecved = req.cbstart; int nLoop = 0; byte[] memory = new byte[10 * 1024]; while (true) { long nTickBegin = DateTime.Now.Ticks; if (!bContinue) { break; } try { nByteRecved = sClient.Receive(memory, 10 * 1024, SocketFlags.None); } catch (Exception exp) { break; } if (nByteRecved <= 0) { break; } nLoop++; //Loader.LogErr("recv bytes:" + nByteRecved.ToString()); req.fs.Write(memory, 0, nByteRecved); req.fs.Flush(); nTotalRecved += nByteRecved; req.cboffset = nTotalRecved; req.loadBytes = nTotalRecved; if (nTotalRecved == nContentLength) { break; } if (nLoop >= 10) { if (req.OnReceivedData != null && !req.bDone) { req.OnReceivedData(ref req); } nLoop = 0; } } sClient.Close(); req.cboffset = req.fs.Seek(0, SeekOrigin.Current); req.fs.Flush(); req.fs.Close(); req.fs = null; if (req.OnReceivedData != null && !req.bDone) { req.OnReceivedData(ref req); } req.bDone = true; } } } if (close != null) { Log.WriteError("thread quit signal open"); close.Set(); close = null; } } catch (Exception exp) { Debug.LogError(exp.Message + "|" + exp.StackTrace + " download thread crashed"); } finally { if (close != null) { close.Set(); close = null; } } }