C# Task<bool>这句是啥意思

各位大神,下面代码中的Task autoRec = Task.Factory.StartNew(() =>这句是什么意思啊,查了半天、还是不理解!
Task autoRec = Task.Factory.StartNew(() =>
{
string newPdtDir = _curPdtDir.Substring(0, _curPdtDir.LastIndexOf("\")) + "\" + copyNewPdtName;
FileModule.CopyDirectory(_curPdtDir, newPdtDir);

            productList_UpdateLst();

            return autoChangeProduct(copyNewPdtName, ref strMsg);
        });
c#

1个回答

Task.Factory.StartNew 启动一个新的线程? 哪里不理解 是不理解写法吗?TaskFactory.StartNew Method (Action) 这个是原函数

https://msdn.microsoft.com/en-us/library/system.action(v=vs.110).aspx 这里面有介绍 action的写法 可以理解为 action就是 这个线程的执行调用方法,

你开启了一个线程,线程是为了做事情,做事情就需要实现怎么做,所以c#里面就是开启一个线程并且指定在这个线程里面执行一个action的意思

ycigwy
雍王爷 是不是可以这样理解:Task.Factory.StartNew(() =>是启动一个新的线程, =>{就是这个线程执行的方法?
大约 3 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
初次使用Task<TResult>关于阻塞主线程求指教

做了一个winform程序,点击一个按钮需要调用一个复杂耗时的方法,总是造成主界面卡死,据说Task可以解决此类情况,就上网查资料模仿,后来发现还是卡死,代码段如下: City ct = (City)cbxCity.SelectedItem; bool checkCom = cBoxDisCom.Checked; Task<DataSet> t = null; t = new Task<DataSet>(() => ImportService.FilterForRaw2(dt, ct, checkCom)); t.Start(); t.Wait(); dgvExportData.DataSource = t.Result.Tables[1]; dgv1.DataSource = t.Result.Tables[0]; 请问有没有办法可以既获取Task产生的结果t.Result,又不会造成主线程阻塞

类中的bool方法组怎么判断真假

Class Guy { public bool PlaceBet(int BetAmount, int DogToWin) { if (Cash >= BetAmount) return true; else return false; } } //创建并实例化了一个guy类数组; private void button2_Click(object sender, EventArgs e) { for (int i = 0; i <= 2; i++) { if(guy[i].PlaceBet==true){ label1.Text="blablablah"; } } } 错误:==无法应用于方法组与bool型操作数,说placebet是一个方法组,怎么回事啊?那我怎么判断guy[i]的真假呢?

以下C++代码如何翻译成C#代码?

``` typedef int s32,BOOL32; #if defined(_WIN64) || defined(WIN64) ||defined (__LP64__) || defined (__64BIT__) || defined (_LP64) || (__WORDSIZE == 64) typedef unsigned int u32; #define KD_PTR void* #else typedef unsigned long u32; #define KD_PTR u32 #endif typedef unsigned char u8; typedef unsigned short u16; typedef short s16; typedef char s8; ``` ``` typedef enum eTransType { emTransChnCOMPort = 0, // 设备COM口透明数据 emTransChnCameraTaskConfig = 1, // 摄像机任务配置数据 emTransChnExtData = 2, // 透明数据,支持请求应答通知三态模型 }TransChnType; typedef struct tagTransData { tagTransData() { memset(m_byTransBuffer,0,sizeof(m_byTransBuffer)); m_wTransBufferLen = 0; m_byAppType = 0; } u8 m_byTransBuffer[MAX_TRANSCHAN_DATA_LEN+1]; u16 m_wTransBufferLen; s8 m_byAppType; } TTransChnData; typedef struct tagTransData_V2 { tagTransData_V2() { memset(m_byTransBuffer,0,sizeof(m_byTransBuffer)); m_wTransBufferLen = 0; m_byAppType = 0; m_TransChnType = emTransChnCOMPort; } u8 m_byTransBuffer[MAX_TRANSCHAN_DATA_LEN+1]; u16 m_wTransBufferLen; u16 m_byAppType; // 透明通道消息类型 TransChnType m_TransChnType; // 透明通道类型 } TTransChnData_V2; typedef struct tagTransData_V3 { tagTransData_V3() { m_pTransBuffer = NULL; m_wTransBufferLen = 0; m_byAppType = 0; m_TransChnType = emTransChnCOMPort; } u8 *m_pTransBuffer; u16 m_wTransBufferLen; // 透明串口数据大小最大值是8KB u16 m_byAppType; // 透明通道消息类型 TransChnType m_TransChnType; // 透明通道类型 } TTransChnData_V3; typedef struct tagTransDataRsp { tagTransDataRsp() { m_pTransBuffer = NULL; m_wTransBufferLen = 0; m_byAppType = 0; memset(m_szUserName, 0, sizeof(m_szUserName)); m_nPtzLevel = 0; m_dwBeginTime = 0; m_dwEndTime = 0; m_bHasNotify = FALSE; m_nErrorCode = 0; memset(m_szErrorDesc, 0, sizeof(m_szErrorDesc)); } u8 *m_pTransBuffer; // 透明通道应答数据,大小至少为8KB。内存由上层应用维护。 u16 m_wTransBufferLen; // 透明通道应答数据大小 u16 m_byAppType; // 透明通道消息类型 char m_szUserName[MAX_NAME_LEN + 1]; int m_nPtzLevel; u32 m_dwBeginTime; u32 m_dwEndTime; BOOL32 m_bHasNotify; int m_nErrorCode; char m_szErrorDesc[MAX_DESC_LEN + 1]; } TTransChnDataRsp; ``` ``` KDM_MCUSDK_API BOOL32 STDCALL Kdm_SendTransData(IN void *pMcuHandle, IN DEVCHN tDevChn, IN TTransChnData *pTransData, OUT u32 *pErrorCode); KDM_MCUSDK_API BOOL32 STDCALL Kdm_SendTransData_V2(IN void *pMcuHandle, IN DEVCHN tDevChn, IN TTransChnData_V2 *pTransData, OUT u32 *pErrorCode); KDM_MCUSDK_API BOOL32 STDCALL Kdm_SendTransData_V3(IN void *pMcuHandle, IN DEVCHN tDevChn, IN TTransChnData_V3 *pTransData, OUT TTransChnDataRsp *pTransDataRsp, OUT u32 *pErrorCode); ``` ``` void CMainFrame::SaveSensorConfigInfo() { u32 dwErrorCode = 0; TCHAR szContent[MAX_PATH] = {0}; CStdString strTemp; strTemp = m_pConfigNvrIDEdit->GetText(); strcpy(m_tSensorCfgParam.achTemID, strTemp.GetData()); strTemp = m_pConfigWidthEdit->GetText(); strcpy(m_tSensorCfgParam.achJieMianKuanDu, strTemp.GetData()); for (int nIndex = 0; nIndex < NVR_MAX_SENSOR_OSD_LINE_NUM; ++nIndex) { strTemp = m_pArrayConfigLineEdit[nIndex]->GetText(); strcpy(m_tSensorCfgParam.achOsdLine[nIndex], strTemp.GetData()); } strTemp = m_pConfigOSDXEdit->GetText(); m_tSensorCfgParam.nOsdX = atoi(strTemp.GetData()); strTemp = m_pConfigOSDYEdit->GetText(); m_tSensorCfgParam.nOsdY = atoi(strTemp.GetData()); strTemp = m_pConfigFtpAddressEdit->GetText(); strcpy(m_tSensorCfgParam.achFtpServerIp, strTemp.GetData()); strTemp = m_pConfigFtpPortEdit->GetText(); m_tSensorCfgParam.wFtpServerPort = atoi(strTemp.GetData()); strTemp = m_pConfigFtpUsrnameEdit->GetText(); strcpy(m_tSensorCfgParam.achFtpServerUsr, strTemp.GetData()); strTemp = m_pConfigFtpPasswordEdit->GetText(); strcpy(m_tSensorCfgParam.achFtpServerPwd, strTemp.GetData()); strTemp = m_pConfigHttpAddressEdit->GetText(); strcpy(m_tSensorCfgParam.achHttpServerIp, strTemp.GetData()); strTemp = m_pConfigHttpPortEdit->GetText(); m_tSensorCfgParam.wHttpServerPort = atoi(strTemp.GetData()); strTemp = m_pConfigHttpUploadURLEdit->GetText(); strcpy(m_tSensorCfgParam.achHttpUpLoadUrl, strTemp.GetData()); strTemp = m_pConfigHttpKeepURLEdit->GetText(); strcpy(m_tSensorCfgParam.achHttpKeepAliveUrl, strTemp.GetData()); int nSel = m_pPlatformNvrCombo->GetCurSel(); if (nSel != -1) { int nTag = m_pPlatformNvrCombo->GetItemAt(nSel)->GetTag(); // 透明传输 DEVCHN devChn; memset(&devChn, 0, sizeof(devChn)); devChn.deviceID = m_vcDevInfo[nTag].deviceID; devChn.domainID = m_vcDevInfo[nTag].domainID; TNvrTransData tNvrTransData; memset(&tNvrTransData, 0, sizeof(tNvrTransData)); tNvrTransData.wNvrMsgType = PLAT_NVR_CONFIG_SENSOR_REQ; tNvrTransData.wNvrBuffLen = sizeof(m_tSensorCfgParam); memcpy(tNvrTransData.m_abyNvrBuff, &m_tSensorCfgParam, sizeof(m_tSensorCfgParam)); TTransChnData_V3 tTransChnData_V3; memset(&tTransChnData_V3, 0, sizeof(tTransChnData_V3)); tTransChnData_V3.m_pTransBuffer = (u8*)&tNvrTransData; tTransChnData_V3.m_wTransBufferLen = sizeof(tNvrTransData); tTransChnData_V3.m_TransChnType = emTransChnExtData; TTransChnDataRsp tTransChnDataRsp; memset(&tTransChnDataRsp, 0, sizeof(tTransChnDataRsp)); tTransChnDataRsp.m_pTransBuffer = m_byteTransChnDataBuffer; tTransChnDataRsp.m_wTransBufferLen = sizeof(m_byteTransChnDataBuffer); BOOL32 bRet = Kdm_SendTransData_V3(m_pMcuSdkHandle, devChn, &tTransChnData_V3, &tTransChnDataRsp, &dwErrorCode); if (!bRet) { sprintf(szContent, "保存设备配置数据失败,errcode:%u", dwErrorCode); GM.DuiMessageBox(m_hWnd, szContent, "kedacom", MB_OK); } else { memset(&tNvrTransData, 0, sizeof(tNvrTransData)); memcpy(&tNvrTransData, m_byteTransChnDataBuffer, sizeof(tNvrTransData)); if (tNvrTransData.wErrorCode != 0) { sprintf(szContent, "保存设备配置数据失败,errcode:%u", tNvrTransData.wErrorCode); GM.DuiMessageBox(m_hWnd, szContent, "kedacom", MB_OK); } } } } ``` 尝试修改为以下C#代码,运行成功,但是执行时候报错: ``` [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)] public struct tagTransData { [MarshalAs(UnmanagedType.ByValArray, SizeConst = 513)] public byte[] m_byTransBuffer; public ushort m_wTransBufferLen; public char m_byAppType; } [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)] public struct tagTransData_V2 { [MarshalAs(UnmanagedType.ByValArray, SizeConst = 513)] public byte[] m_byTransBuffer; public ushort m_wTransBufferLen; public ushort m_byAppType; // 透明通道消息类型 public eTransType m_TransChnType; // 透明通道类型 } [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)] public unsafe struct tagTransData_V3 { public byte* m_pTransBuffer; public ushort m_wTransBufferLen; // 透明串口数据大小最大值是8KB public ushort m_byAppType; // 透明通道消息类型 public eTransType m_TransChnType; // 透明通道类型 } [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)] public unsafe struct tagTransDataRsp { public byte* m_pTransBuffer; // 透明通道应答数据,大小至少为8KB。内存由上层应用维护。 public ushort m_wTransBufferLen; // 透明通道应答数据大小 public ushort m_byAppType; // 透明通道消息类型 public char* m_szUserName; public int m_nPtzLevel; public uint m_dwBeginTime; public uint m_dwEndTime; public uint m_bHasNotify; public int m_nErrorCode; public char* m_szErrorDesc; } ``` ``` [DllImport(@"mcusdk.dll")] public extern static uint Kdm_SendTransData(IntPtr pMcuHandle, DEVCHN tDevChn, tagTransData pTransData, ref uint pErrorCode); [DllImport(@"mcusdk.dll")] public extern static uint Kdm_SendTransData_V2(IntPtr pMcuHandle, DEVCHN tDevChn, tagTransData_V2 TransData, ref uint pErrorCode); [DllImport(@"mcusdk.dll")] public extern static uint Kdm_SendTransData_V3(IntPtr pMcuHandle, DEVCHN tDevChn, tagTransData_V3 pTransData, ref tagTransDataRsp pTransDataRsp, ref uint pErrorCode); ``` ``` private unsafe void btnSave_Click(object sender, EventArgs e) { uint dwErrorCode = 0; TSensorCfgParam m_tSensorCfgParam=new TSensorCfgParam(); sbyte[] szContent = new sbyte[DefineConstants.MAX_PATH]; m_tSensorCfgParam.achTemID = txtNVRID.Text; m_tSensorCfgParam.achJieMianKuanDu = txtWidth.Text; //for (int nIndex = 0; nIndex < NVR_MAX_SENSOR_OSD_LINE_NUM; ++nIndex) //{ // strTemp = m_pArrayConfigLineEdit[nIndex].GetText(); // m_tSensorCfgParam.achOsdLine[nIndex] = strTemp.GetData(); //} //strTemp = m_pConfigOSDXEdit.GetText(); //m_tSensorCfgParam.nOsdX = Convert.ToInt32(strTemp.GetData()); //strTemp = m_pConfigOSDYEdit.GetText(); //m_tSensorCfgParam.nOsdY = Convert.ToInt32(strTemp.GetData()); //strTemp = m_pConfigFtpAddressEdit.GetText(); //m_tSensorCfgParam.achFtpServerIp = strTemp.GetData(); //strTemp = m_pConfigFtpPortEdit.GetText(); //m_tSensorCfgParam.wFtpServerPort = Convert.ToInt32(strTemp.GetData()); //strTemp = m_pConfigFtpUsrnameEdit.GetText(); //m_tSensorCfgParam.achFtpServerUsr = strTemp.GetData(); //strTemp = m_pConfigFtpPasswordEdit.GetText(); //m_tSensorCfgParam.achFtpServerPwd = strTemp.GetData(); //strTemp = m_pConfigHttpAddressEdit.GetText(); //m_tSensorCfgParam.achHttpServerIp = strTemp.GetData(); //strTemp = m_pConfigHttpPortEdit.GetText(); //m_tSensorCfgParam.wHttpServerPort = Convert.ToInt32(strTemp.GetData()); //strTemp = m_pConfigHttpUploadURLEdit.GetText(); //m_tSensorCfgParam.achHttpUpLoadUrl = strTemp.GetData(); //strTemp = m_pConfigHttpKeepURLEdit.GetText(); //m_tSensorCfgParam.achHttpKeepAliveUrl = strTemp.GetData(); int nSel = lbDevice.SelectedIndex; if (nSel != -1) { //int nTag = m_pPlatformNvrCombo.GetItemAt(nSel).GetTag(); // 透明传输 DEVCHN devChn = new DEVCHN(); //C++ TO C# CONVERTER CRACKED BY X-CRACKER 2017 TODO TASK: The memory management function 'memset' has no equivalent in C#: //Comm.memset(devChn, 0, sizeof(DEVCHN)); devChn.deviceID = deviceList[nSel].deviceID; devChn.domainID = deviceList[nSel].domainID; TNvrTransData tNvrTransData = new TNvrTransData(); //C++ TO C# CONVERTER CRACKED BY X-CRACKER 2017 TODO TASK: The memory management function 'memset' has no equivalent in C#: //Comm.memset(tNvrTransData, 0, sizeof(TNvrTransData)); tNvrTransData.wNvrMsgType = DefineConstants.PLAT_NVR_CONFIG_SENSOR_REQ; //tNvrTransData.wNvrBuffLen = sizeof(m_tSensorCfgParam); //C++ TO C# CONVERTER CRACKED BY X-CRACKER 2017 TODO TASK: The memory management function 'memcpy' has no equivalent in C#: //Comm.memcpy(tNvrTransData.m_abyNvrBuff, m_tSensorCfgParam, sizeof(m_tSensorCfgParam)); tagTransData_V3 tTransChnData_V3 = new tagTransData_V3(); //C++ TO C# CONVERTER CRACKED BY X-CRACKER 2017 TODO TASK: The memory management function 'memset' has no equivalent in C#: //Comm.memset(tTransChnData_V3, 0, sizeof(TTransChnData_V3)); tTransChnData_V3.m_pTransBuffer = (byte)&tNvrTransData; //tTransChnData_V3.m_pTransBuffer = (byte*) ref (tNvrTransData)[0]; //tTransChnData_V3.m_wTransBufferLen = sizeof(TNvrTransData); tTransChnData_V3.m_TransChnType = eTransType.emTransChnExtData; tagTransDataRsp tTransChnDataRsp = new tagTransDataRsp(); //C++ TO C# CONVERTER CRACKED BY X-CRACKER 2017 TODO TASK: The memory management function 'memset' has no equivalent in C#: //Comm.memset(tTransChnDataRsp, 0, sizeof(tagTransDataRsp)); m_byteTransChnDataBuffer = new byte[8 * 1024]; tTransChnDataRsp.m_pTransBuffer = (byte*)m_byteTransChnDataBuffer[0]; //tTransChnDataRsp.m_wTransBufferLen = sizeof(m_byteTransChnDataBuffer); uint bRet = myAPI.Kdm_SendTransData_V3(mcuHandle, devChn, tTransChnData_V3, ref tTransChnDataRsp, ref dwErrorCode); if (bRet == 0) { //szContent = string.Format("保存设备配置数据失败,errcode:{0:D}", dwErrorCode); //GM.DuiMessageBox(m_hWnd, szContent, "kedacom", MB_OK); } else { //C++ TO C# CONVERTER CRACKED BY X-CRACKER 2017 TODO TASK: The memory management function 'memset' has no equivalent in C#: //memset(tNvrTransData, 0, sizeof(TNvrTransData)); //C++ TO C# CONVERTER CRACKED BY X-CRACKER 2017 TODO TASK: The memory management function 'memcpy' has no equivalent in C#: //memcpy(tNvrTransData, m_byteTransChnDataBuffer, sizeof(TNvrTransData)); if (tNvrTransData.wErrorCode != 0) { //szContent = string.Format("保存设备配置数据失败,errcode:{0:D}", tNvrTransData.wErrorCode); //GM.DuiMessageBox(m_hWnd, szContent, "kedacom", MB_OK); } } } } ``` 求大神翻译

c# winform 多线程异常无法捕获,导致程序闪退

伪代码为: try { if (helper.TogetherBookThread != null && helper.TogetherBookThread.IsAlive) { return; } helper.TogetherBookThread = new Thread(new ThreadStart(delegate() { try { while (true) { if (helper.TicketQuery != null) { Dictionary<string, TicketOrderCSun> TicketOrderCSunDic = helper.TicketQuery.TicketOrderCSunDic; foreach (var cSun in TicketOrderCSunDic.Values) { bool flag = helper.DetermineBookOrderNewAction(cSun, helper); if (flag) { Thread.CurrentThread.Abort(); } } } Thread.Sleep(1); } } catch (ThreadAbortException) { } catch (Exception ex) { if (!(ex is ThreadAbortException)) { NetTicketCommonUtil.WriteTicketInfo("TogetherBookDetermineBookOrderThread " + ex.Message + " source:" + ex.StackTrace); } } })); helper.TogetherBookThread.IsBackground = true; helper.TogetherBookThread.Priority = ThreadPriority.Highest; helper.TogetherBookThread.Start(); //helper.TogetherBookThread.IsBackground = true; //helper.TogetherBookThread.Priority = ThreadPriority.Highest; ////helper.TogetherBookThread.ApartmentState = ApartmentState.STA; //helper.TogetherBookThread.Start(); } catch (Exception ex) { if (!(ex is ThreadAbortException)) { NetTicketCommonUtil.WriteTicketInfo("TogetherBookDetermineBookOrderThreadAAA:" + ex.Message + " source:" + ex.StackTrace); } } 每隔一毫秒就在里面判断是否有执行的任务,如果,有任务执行,并且成功,就退出线程。但是经常出现闪退。程序外面我已经加了全局捕获。但是无法捕获闪退日志。我查看windows日志,提示。 Framework Version: v4.0.30319 Description: The process was terminated due to an unhandled exception. Exception Info: System.NullReferenceException Stack: at NetTicket.Actions.NetTicketHelper+<>c__DisplayClassc.<TogetherBookDetermineBookOrderMainAction>b__a() at System.Threading.ThreadHelper.ThreadStart_Context(System.Object) at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean) at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean) at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object) at System.Threading.ThreadHelper.ThreadStart() 提示空指针异常。我里面都执行都是try catch过。不明白为什么闪退。全局都是无提示的。。找了很久不知道原因

C# Socket服务器接收HTTP请求,不能全部做出响应

使用Socket作为服务器,接收HTTP请求,在Socket socket = socketListen.Accept();之后启动一个线程处理接收数据 和发送数据,如果不调用socket.Receive(data);接收客户数据的话,那么客户端(也就是HTTP请求)请求多少次, 服务端的Socket socket = socketListen.Accept();就会被调用多少次,就是能百分百接收到客户端请求, 但是通过socket.Send(head)作为HTTP请求返回数据,HTTP请求那边几乎获取不到返回的数据, 偶尔还是能获取到的,相反,不调用socket.Receive(data);方法,就会出现 比如 HTTP请求了100次, socketListen.Accept();可能就被执行了80次,但是这80次调用socket.Send(head)返回给http的数据,http那边都能获取到服务端返回的数据,注:客户端每次发送的数据很少,代码如下public partial class MainWindow : Window { private Socket socketWatch; private Thread listenThread = null; private bool isRun = false; private int pointer = 0; public MainWindow() { InitializeComponent(); init(); } private void init() { socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socketWatch.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 80)); socketWatch.Listen(10); // 参数表示最多可容纳的等待接受的传入连接数,不包含已经建立连接的 listenThread = new Thread(new ParameterizedThreadStart(run)); listenThread.IsBackground = true; } private void run(Object o) { Socket socketListen = (Socket)o; while (isRun) { Socket socket = socketListen.Accept(); pointer = pointer + 1; Thread thread = new Thread(new ParameterizedThreadStart(task)); thread.IsBackground = true; thread.Start(socket); } } private void bn_start_Click(object sender, RoutedEventArgs e) { isRun = true; bn_start.IsEnabled = false; bn_stop.IsEnabled = true; listenThread.Start(socketWatch); } private void bn_stop_Click(object sender, RoutedEventArgs e) { System.Environment.Exit(0); } private void Window_Closed(object sender, EventArgs e) { System.Environment.Exit(0); } private void task(object o) { Socket socket = (Socket)o; byte[] data = new byte[1024 * 2]; // 浏览器发来的数据 int reciverNumber = socket.Receive(data); string resdata = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " server request time:" + pointer; byte[] body = Encoding.UTF8.GetBytes(resdata); byte[] head = Encoding.UTF8.GetBytes(@"HTTP/1.1 200 OK Content-Length: " + body.Length + @" Content-Type: text/plain Date: " + string.Format("{0:R}", DateTime.Now) + @" Server: Cftea Web Server " + resdata); socket.Send(head); socket.Shutdown(SocketShutdown.Both); socket.Close(); } } ``` ```

c# 线程间操作无效 从不是创建控件“listView1”的线程访问它

![图片说明](https://img-ask.csdn.net/upload/201912/02/1575253835_918613.jpg) private void button2_Click(object sender, EventArgs e) { Lrcload ld = new Lrcload(); ld.code = Encoding.Default; if (dcgb2312.Checked) ld.code = System.Text.Encoding.GetEncoding("gb2312"); if (dcutf8.Checked) ld.code = System.Text.Encoding.GetEncoding("utf-8"); ld.listview = listView1.Items; ld.reload = checkBox3.Checked; //ld.load(); Thread t = new Thread(new ThreadStart(ld.load)); t.IsBackground = true; t.Start(); } class Lrcload { /// <summary> /// 保存文件编码 /// </summary> public System.Text.Encoding code; /// <summary> /// 列表listview.Items /// </summary> // public ListViewItem[] listview; public ListView.ListViewItemCollection listview; /// <summary> /// 已有歌词重下 /// </summary> public bool reload; /// <summary> /// 下载歌词 /// </summary> public void load() { bu(false); foreach (ListViewItem lvi in listview) { try {

c#异步通信代码错误问题

public void ConnectCallback(IAsyncResult ar) { Socket client = (Socket)ar.AsyncState; client.EndConnect(ar); bool connect_flag = false; connect_flag = true; ManualResetEvent connectDone = new ManualResetEvent(false); //连接的信号 connectDone.Set(); } //vs的这段代码中 ,bool connect_flag的connect_flag报了一个警告错误,变量connect_flag已赋值,但是其值从未使用过。如何修改? public static MODEL.DataSourceVersionQuery BrowseDataSource_QueryVersionData() { MODEL.DataSourceVersionQuery result = new MODEL.DataSourceVersionQuery(); //获取数据包 string strPacket = BrowseDataSource_PrepareVersionPacket(); //向服务端提交查询版本信息 string str = DAL.socket.GetSocketData(strPacket); //DAL.socket.GetSocketData(strPacket) vs报了一个错误,非静态字段、方法或属性DAL.socket.GetSocketData(string)“要求对象引用。如何修改? 还有这个错误![图片说明](https://img-ask.csdn.net/upload/201509/16/1442412249_893824.png) 另外我想把DAL中的socket.cs的 public byte[] bytesReceived { get; set; }这段移动到Model中而不报错要如何修改? DAL中socket完整代码如下: using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; using System.ComponentModel; using System.Data; using System.Windows.Forms; using System.Threading; namespace DAL { /// <summary> /// Socket接口 /// </summary> class socket { //Socket public Socket clientSocket; /// <summary> /// socket连接 /// </summary> /// <returns> /// true 成功 /// false 失败 /// </returns> public bool SocketConnect() { byte[] bytesReceived = new byte[256]; ManualResetEvent connectDone = new ManualResetEvent(false); //连接的信号 ManualResetEvent sendDone = new ManualResetEvent(false); //发送结束 //从配置文件获取IP string SocketIP = DAL.Common.ReadConfigString("Recover", "IP"); //从配置文件获取端口 int SocketPort = Convert.ToInt32(DAL.Common.ReadConfigString("Recover", "Port")); //创建IP地址 IPAddress IP = IPAddress.Parse(SocketIP); try { //创建socket实例 clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //创建网络端点 IPEndPoint ipEnd = new IPEndPoint(IP, SocketPort); //与目标终端连接 clientSocket.BeginConnect(ipEnd, new AsyncCallback(ConnectCallback), clientSocket);//调用回调函数 connectDone.WaitOne(); if (clientSocket.Connected) { return true; } else { return false; } } catch (Exception e) { string strError = ""; strError += "\r\n SocketIP = " + SocketIP.ToString(); strError += "\r\n SocketPort = " + SocketPort.ToString(); DAL.Common.WriteErrorLog(e, strError); return false; } } /// <summary> /// 异步连接的回调函数 /// </summary> /// <param name="ar"></param> public void ConnectCallback(IAsyncResult ar) { Socket client = (Socket)ar.AsyncState; client.EndConnect(ar); bool connect_flag = false; connect_flag = true; ManualResetEvent connectDone = new ManualResetEvent(false); //连接的信号 connectDone.Set(); } /// <summary> /// Socket发送数据 /// </summary> /// <param name="strSend"> /// 数据的内容 /// </param> public void SocketSend(string strSend) { Socket clientSocket; //发送创建套接字 int length = strSend.Length; Byte[] bytesSent = new byte[length]; clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { bytesSent = System.Text.Encoding.Default.GetBytes(strSend); //将字符串指定到指定Byte数组 clientSocket.BeginSend(bytesSent, 0, bytesSent.Length, 0, new AsyncCallback(SendCallback), clientSocket); //异步发送数据 ManualResetEvent sendDone = new ManualResetEvent(false);//发送结束 sendDone.WaitOne(); } catch (Exception e) { string strError = ""; DAL.Common.WriteErrorLog(e, strError); } } public void SendCallback(IAsyncResult ar) //发送的回调函数 { ManualResetEvent sendDone = new ManualResetEvent(false); //发送结束 Socket client = (Socket)ar.AsyncState; int bytesSend = client.EndSend(ar); //完成发送 sendDone.Set(); } /// <summary> /// Socket接收数据 /// </summary> /// <returns> /// 收到的数据 /// </returns> public string SocketReceive() { string result = ""; try { MemoryStream stream = new MemoryStream(); Byte[] bytesReceived = new Byte[256]; clientSocket.BeginReceive(bytesReceived, 0, bytesReceived.Length, 0, new AsyncCallback(ReceiveCallback), clientSocket); ManualResetEvent sendDone = new ManualResetEvent(false); //发送结束 sendDone.WaitOne(); } catch (Exception e) { string strError = ""; DAL.Common.WriteErrorLog(e, strError); } return result; } public void ReceiveCallback(IAsyncResult ar) { Socket client = (Socket)ar.AsyncState; //获取句柄 int bytesread = client.EndReceive(ar); if (bytesread > 0) { clientSocket.BeginReceive(bytesReceived, 0, bytesReceived.Length, 0, new AsyncCallback(ReceiveCallback), client); string content = Encoding.ASCII.GetString(bytesReceived, 0, bytesReceived.Length); } else { ManualResetEvent readDone = new ManualResetEvent(false); //读信号 readDone.Set(); } } /// <summary> /// Socket通信 /// </summary> /// <param name="strSend"> /// 发送的信息 /// </param> /// <returns> /// 包体的内容 /// </returns> public string GetSocketData(string strSend) { string strDatas = ""; string strResult = ""; string strExtLength = ""; try { //Socket连接 SocketConnect(); //发送信息 SocketSend(strSend); //接收服务器的信息 strResult = SocketReceive(); //获取扩展信息的长度 strExtLength = strResult.Substring(16, 12); int ExtLength = Convert.ToInt32(strExtLength); //扩展信息,暂不使用 //string strExtInfo = strResult.Substring(32, ExtLength); //获取包体的内容 strDatas = strResult.Substring(ExtLength + 32); //strDatas = decodedString; } catch (Exception e) { string strError = ""; strError += "\r\n strResult = " + strResult; strError += "\r\n strExtLength = " + strExtLength; DAL.Common.WriteErrorLog(e, strError); strDatas = ""; } return strDatas; } public string SocketReceiveFile(string FileName) { string result = ""; try { MemoryStream streamPacketLength = new MemoryStream(); Byte[] bytesPacketLength = new Byte[16]; clientSocket.Receive(bytesPacketLength, bytesPacketLength.Length, 0); streamPacketLength.Write(bytesPacketLength, 0, bytesPacketLength.Length); result = System.Text.Encoding.Default.GetString(streamPacketLength.ToArray()); int PacketLength = Convert.ToInt32(result); streamPacketLength.Close(); MemoryStream streamExtLength = new MemoryStream(); Byte[] bytesExtLength = new Byte[12]; clientSocket.Receive(bytesExtLength, bytesExtLength.Length, 0); streamExtLength.Write(bytesExtLength, 0, bytesExtLength.Length); result = System.Text.Encoding.Default.GetString(streamExtLength.ToArray()); int ExtLength = Convert.ToInt32(result); streamExtLength.Close(); MemoryStream streamProtocol = new MemoryStream(); Byte[] bytesProtocol = new Byte[4]; clientSocket.Receive(bytesProtocol, bytesProtocol.Length, 0); streamProtocol.Write(bytesProtocol, 0, bytesProtocol.Length); result = System.Text.Encoding.Default.GetString(streamProtocol.ToArray()); string Protocol = result; streamProtocol.Close(); MemoryStream streamExtInfo = new MemoryStream(); Byte[] bytesExtInfo = new Byte[ExtLength]; clientSocket.Receive(bytesExtInfo, bytesExtInfo.Length, 0); streamExtInfo.Write(bytesExtInfo, 0, bytesExtInfo.Length); result = System.Text.Encoding.Default.GetString(streamExtInfo.ToArray()); byte[] Buffer = Convert.FromBase64String(result); string strExtInfo = UTF8Encoding.UTF8.GetString(Buffer); streamExtInfo.Close(); MODEL.FileTrackQuery ExtInfo = new MODEL.FileTrackQuery(); ExtInfo = JsonConvert.DeserializeObject<MODEL.FileTrackQuery>(strExtInfo); if (ExtInfo.code == "00") { FileInfo fi = new FileInfo(FileName); DirectoryInfo di = fi.Directory; if (!di.Exists) { di.Create(); } FileStream streamPacketInfo = new FileStream(FileName, FileMode.Create); if (PacketLength > 0) { Byte[] bytesPacketInfo = new Byte[PacketLength]; int bytes = 0; do { bytes = clientSocket.Receive(bytesPacketInfo, bytesPacketInfo.Length, 0); streamPacketInfo.Write(bytesPacketInfo, 0, bytes); } while (bytes > 0); } streamPacketInfo.Close(); } clientSocket.Close(); string strLogFile = System.AppDomain.CurrentDomain.BaseDirectory + "debug.txt"; StreamWriter sw = new StreamWriter(strLogFile, true); sw.WriteLine("PacketLength : " + PacketLength.ToString()); sw.WriteLine("ExtLength : " + ExtLength.ToString()); sw.WriteLine("strExtInfo : " + strExtInfo); sw.WriteLine("ExtInfo.code : " + ExtInfo.code); sw.WriteLine("\n------------------------------------------------------------------------\n"); sw.Flush(); sw.Close(); } catch (Exception e) { string strError = ""; DAL.Common.WriteErrorLog(e, strError); } return result; } public string GetSocketFile(string strSend, string FileName) { string strDatas = ""; string strResult = ""; string strExtLength = ""; try { //Socket连接 SocketConnect(); //发送信息 SocketSend(strSend); //接收服务器的信息 strResult = SocketReceiveFile(FileName); //获取扩展信息的长度 //strExtLength = strResult.Substring(16, 12); //int ExtLength = Convert.ToInt32(strExtLength); //扩展信息,暂不使用 //string strExtInfo = strResult.Substring(32, ExtLength); //获取包体的内容 //strDatas = strResult.Substring(ExtLength + 32); } catch (Exception e) { string strError = ""; strError += "\r\n strResult = " + strResult; strError += "\r\n strExtLength = " + strExtLength; DAL.Common.WriteErrorLog(e, strError); strDatas = ""; } return strDatas; } public byte[] bytesReceived { get; set; } } } MODEL完整代码如下: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MODEL { public enum ClientEditionEnum { Enterprise,//企业版 Personal,//个人版 Internal,//内部版 None,//error } /// <summary> /// 授权文件内容 /// </summary> public class AuthorizeFileInfo { public string startTime { get; set; } public string expiryTime { get; set; } public string licenseID { get; set; } public string licensePassword { get; set; } public string terminalID { get; set; } public string customName { get; set; } public string customID { get; set; } public AuthorizeFileInfo() { startTime = ""; expiryTime = ""; licenseID = ""; licensePassword = ""; terminalID = ""; customName = ""; customID = ""; } } /// <summary> /// 通用返回值 /// </summary> /// public class CommonResult { public string code { get; set; } public string message { get; set; } public CommonResult() { code = ""; message = ""; } } public class EnterpriseConfirmAuthorizeDatas { public string sessionID { get; set; } public EnterpriseConfirmAuthorizeDatas() { sessionID = ""; } } /// <summary> /// 企业版授权校验接口 /// </summary> public class EnterpriseConfirmAuthorizeResult { public string code { get; set; } public string message { get; set; } public EnterpriseConfirmAuthorizeDatas datas { get; set; } public EnterpriseConfirmAuthorizeResult() { code = ""; message = ""; datas = new EnterpriseConfirmAuthorizeDatas(); } } public class PersonalConfirmAuthorizeDatas { public string sessionID { get; set; } public string licenseInfo { get; set; } public PersonalConfirmAuthorizeDatas() { sessionID = ""; licenseInfo = ""; } } /// <summary> /// 个人版授权校验接口 /// </summary> public class PersonalConfirmAuthorizeResult { public string code { get; set; } public string message { get; set; } public PersonalConfirmAuthorizeDatas datas { get; set; } public PersonalConfirmAuthorizeResult() { code = ""; message = ""; datas = new PersonalConfirmAuthorizeDatas(); } } /// <summary> /// 鉴权信息,每次调用安全接口时使用 /// </summary> public class LicInfo { public string licenseID { get; set; } public string licensePassword { get; set; } public string terminalID { get; set; } public string deviceID { get; set; } public string sessionID { get; set; } public LicInfo() { licenseID = ""; licensePassword = ""; terminalID = ""; deviceID = ""; sessionID = ""; } } /// <summary> /// java引擎的参数 /// </summary> public class JavaEngineArg { public string licenseID { get; set; } public string licensePassword { get; set; } public string terminalID { get; set; } public string customName { get; set; } public string customID { get; set; } public string deviceID { get; set; } public JavaEngineArg() { licenseID = ""; licensePassword = ""; terminalID = ""; customName = ""; customID = ""; deviceID = ""; } } /// <summary> /// 用户登录接口(一),非安全接口 /// </summary> /// public class UserInfoUnSafe { public string userID { get; set; } public string userName { get; set; } public string departmentName { get; set; } public UserInfoUnSafe() { userID = ""; userName = ""; departmentName = ""; } } public class UserLoginUnSafe { public string code { get; set; } public string message { get; set; } public UserInfoUnSafe datas { get; set; } public UserLoginUnSafe() { code = ""; message = ""; datas = new UserInfoUnSafe(); } } /// <summary> /// 个人版用户登录接口,非安全接口 /// </summary> /// public class UserInfoForPersonal { public string userID { get; set; } public string userName { get; set; } public string departmentName { get; set; } public string licenseInfo { get; set; } public UserInfoForPersonal() { userID = ""; userName = ""; departmentName = ""; licenseInfo = ""; } } public class UserLoginForPersonal { public string code { get; set; } public string message { get; set; } public UserInfoForPersonal datas { get; set; } public UserLoginForPersonal() { code = ""; message = ""; datas = new UserInfoForPersonal(); } } /// <summary> /// 用户登录接口(二),安全接口 /// </summary> /// public class UserInfoSafe { public string userSessionID { get; set; } public string userID { get; set; } public string userName { get; set; } public string departmentName { get; set; } public string activeTime { get; set; } public UserInfoSafe() { userSessionID = ""; userID = ""; userName = ""; departmentName = ""; activeTime = ""; } } public class UserLoginSafe { public string code { get; set; } public string message { get; set; } public UserInfoSafe datas { get; set; } public UserLoginSafe() { code = ""; message = ""; datas = new UserInfoSafe(); } } /// <summary> /// 更新检查接口 /// </summary> /// public class SingleVersion { public string softID { get; set; } public int version { get; set; } public SingleVersion() { softID = ""; version = new int(); } } public class Versions { public List<SingleVersion> versions { get; set; } public Versions() { versions = new List<SingleVersion>(); } } public class VersionUpdate { public string softID { get; set; } public int version { get; set; } public string url { get; set; } public VersionUpdate() { softID = ""; version = new int(); url = ""; } } public class VersionCheck { public string code { get; set; } public string message { get; set; } public List<VersionUpdate> datas { get; set; } public VersionCheck() { code = ""; message = ""; datas = new List<VersionUpdate>(); } } /// <summary> /// 数据源信息查询接口 /// </summary> /// public class OptInfoQuery { public string createUserID { get; set; } public string createUserName { get; set; } public string createUserTime { get; set; } public OptInfoQuery() { createUserID = ""; createUserName = ""; createUserTime = ""; } } public class Period { public int cycle { get; set; } public int cycleUnit { get; set; } public string timer { get; set; } public Period() { cycle = 1; cycleUnit = 1; timer = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"); } } public class StrategyConfig { public int backType { get; set; } public int taskType { get; set; } public Period config { get; set; } public StrategyConfig() { backType = 0; taskType = 1; config = new Period(); } } public class FilterFileSuffix { public string suffix { get; set; } public FilterFileSuffix() { suffix = ""; } } public class Scan { public int scanType { get; set; } public string root { get; set; } public bool scanHideFile { get; set; } public string verifyCompleteName { get; set; } public int verifyCompleteMaxCount { get; set; } public int verifyCompleteTimer { get; set; } public string fileAttrGainer { get; set; } public bool recordCanNotReadFileInfo { get; set; } public bool recordEmptyDirectory { get; set; } public bool recordEmptyFile { get; set; } public List<FilterFileSuffix> filterFileSuffix { get; set; } public Scan() { scanType = 2; root = ""; scanHideFile = false; verifyCompleteName = ""; verifyCompleteMaxCount = 5; verifyCompleteTimer = 10000; fileAttrGainer = "null"; recordCanNotReadFileInfo = false; recordEmptyDirectory = false; recordEmptyFile = false; filterFileSuffix = new List<FilterFileSuffix>(); } } public class DataSourceConfigQuery { public int status { get; set; } public int dataSourceType { get; set; } public string dataSourceID { get; set; } public string dataSourceName { get; set; } public string dataSourceDescription { get; set; } public Scan config { get; set; } public DataSourceConfigQuery() { status = 0; dataSourceType = 0; dataSourceID = ""; dataSourceName = ""; dataSourceDescription = ""; config = new Scan(); } } public class DatasQuery { public OptInfoQuery optInfo { get; set; } public StrategyConfig strategyConfig { get; set; } public DataSourceConfigQuery dataSourceConfig { get; set; } public DatasQuery() { optInfo = new OptInfoQuery(); strategyConfig = new StrategyConfig(); dataSourceConfig = new DataSourceConfigQuery(); } } public class DataSourceInfoQuery { public string code { get; set; } public string message { get; set; } public List<DatasQuery> datas { get; set; } public DataSourceInfoQuery() { code = ""; message = ""; datas = new List<DatasQuery>(); } } public class WebSite { public string ExpirationTime { get; set; } public string WebSiteSpace { get; set; } public bool DataBaseEnable { get; set; } public string DataBaseUserName { get; set; } public string DataBasePassword { get; set; } public string DataBaseMark { get; set; } public string WebSiteAdmin { get; set; } public string WebSitePassword { get; set; } public WebSite() { ExpirationTime = ""; WebSiteSpace = ""; DataBaseEnable = false; DataBaseUserName = ""; DataBasePassword = ""; DataBaseMark = ""; WebSiteAdmin = ""; WebSitePassword = ""; } } public class WebSiteDatasQuery { public OptInfoQuery optInfo { get; set; } public StrategyConfig strategyConfig { get; set; } public DataSourceConfigQuery dataSourceConfig { get; set; } public WebSite webSiteConfig { get; set; } public WebSiteDatasQuery() { optInfo = new OptInfoQuery(); strategyConfig = new StrategyConfig(); dataSourceConfig = new DataSourceConfigQuery(); webSiteConfig = new WebSite(); } } public class WebSiteDataSourceInfoQuery { public string code { get; set; } public string message { get; set; } public List<WebSiteDatasQuery> datas { get; set; } public WebSiteDataSourceInfoQuery() { code = ""; message = ""; datas = new List<WebSiteDatasQuery>(); } } /// <summary> /// 新增数据源接口 /// </summary> /// public class OptInfoNew { public bool forceFlag { get; set; } public OptInfoNew() { forceFlag = true; } } public class DataSourceConfigNew { public int dataSourceType { get; set; } public string dataSourceName { get; set; } public string dataSourceDescription { get; set; } public Scan config { get; set; } public DataSourceConfigNew() { dataSourceType = 0; dataSourceName = ""; dataSourceDescription = ""; config = new Scan(); } } public class DataSourceNew { public OptInfoNew optInfo { get; set; } public StrategyConfig strategyConfig { get; set; } public DataSourceConfigNew dataSourceConfig { get; set; } public DataSourceNew() { optInfo = new OptInfoNew(); strategyConfig = new StrategyConfig(); dataSourceConfig = new DataSourceConfigNew(); } } /// <summary> /// 修改数据源接口 /// </summary> /// public class DataSourceModify { public StrategyConfig strategyConfig { get; set; } public DataSourceConfigQuery dataSourceConfig { get; set; } public DataSourceModify() { strategyConfig = new StrategyConfig(); dataSourceConfig = new DataSourceConfigQuery(); } } /// <summary> /// 停用/启用数据源接口 /// </summary> /// public class DataSourceStatus { public string dataSourceID { get; set; } public int optType { get; set; } public DataSourceStatus() { dataSourceID = ""; optType = new int(); } } /// <summary> /// 数据源数据,仅用于存放数据 /// </summary> /// public class DataSourceData { public List<DatasQuery> datas { get; set; } public DataSourceData() { datas = new List<DatasQuery>(); } } /// <summary> /// WebSite数据源数据,仅用于存放数据 /// </summary> /// public class WebSiteDataSourceData { public List<WebSiteDatasQuery> datas { get; set; } public WebSiteDataSourceData() { datas = new List<WebSiteDatasQuery>(); } } /// <summary> /// 文件恢复,版本查询 /// </summary> /// public class DataSourceVersionArg { // 通讯令牌 public string secretKey { get; set; }//由token进过MD5->BASE64->MD5获得 // 任务令牌 public string token { get; set; }//客户端生成一个UUID // 前置机编号 public string terminalId { get; set; } // 操作用户编号 public string optUserID { get; set; } public DataSourceVersionArg() { secretKey = ""; token = ""; terminalId = ""; optUserID = ""; } } public class FileVersions { public int file_count { get; set; } public long space_size { get; set; } public string task_id { get; set; } public string task_time { get; set; } public int total_count { get; set; } public string version { get; set; } public FileVersions() { file_count = new int(); space_size = new long(); task_id = ""; task_time = ""; total_count = new int(); version = ""; } } public class DataSourceVersion { public Scan datasourceConfig { get; set; } public string datasourceId { get; set; } public string datasourceName { get; set; } public int datasourceStatus { get; set; } public int datasourceType { get; set; } public List<FileVersions> versions { get; set; } public DataSourceVersion() { datasourceConfig = new Scan(); datasourceId = ""; datasourceName = ""; datasourceStatus = new int(); datasourceType = new int(); versions = new List<FileVersions>(); } } /// <summary> /// 查询数据源接口 /// </summary> public class DataSourceVersionQuery { public string code { get; set; } public string message { get; set; } public List<DataSourceVersion> datas { get; set; } public DataSourceVersionQuery() { code = ""; message = ""; datas = new List<DataSourceVersion>(); } } /// <summary> /// 数据源版本信息 /// </summary> public class DataSourceVersionDatas { public List<DataSourceVersion> datas { get; set; } public DataSourceVersionDatas() { datas = new List<DataSourceVersion>(); } } /// <summary> /// 文件恢复,文件信息查询 /// </summary> /// public class QueryFileInfoArg { // 通讯令牌 public string secretKey { get; set; }//由token进过MD5->BASE64->MD5获得 // 任务令牌 public string token { get; set; }//客户端生成一个UUID // 数据源编号 public string datasourceId { get; set; } // 操作用户编号 public string optUserID { get; set; } // 目录文件编号--如果为根目录使用 DS_ROOT public string fileID { get; set; } // 查询的版本编号 如果是综合分析 这个字段设置为 ALL public string taskID { get; set; } public QueryFileInfoArg() { secretKey = ""; token = ""; datasourceId = ""; optUserID = ""; fileID = ""; taskID = ""; } } public class FileInfoCondition { public string datasourceId { get; set; } public string parentId { get; set; } public string taskID { get; set; } public FileInfoCondition() { datasourceId = ""; parentId = ""; taskID = ""; } } public class FileInfo { // 文件唯一编号 public string file_id { get; set; } // 源相对目录 public string file_src_path { get; set; } // 文件名 public string file_name { get; set; } // 文件后缀 public string file_suffix { get; set; } // 是否为文件 public bool is_file { get; set; } // 上级文件编号 public string parent_id { get; set; } // 是否删除 public bool is_del { get; set; } // 是否隐藏 public bool is_hide { get; set; } // 文件大小 public int size { get; set; } // 文件创建时间 public string create_time { get; set; } // 文件创建人 public string create_user { get; set; } // 文件最后修改时间 public string lm_time { get; set; } // 文件最后修改人 public string lm_user { get; set; } // 是否可读 public bool can_read { get; set; } public FileInfo() { file_id = ""; file_src_path = ""; file_name = ""; file_suffix = ""; is_file = new bool(); parent_id = ""; is_del = new bool(); is_hide = new bool(); size = new int(); create_time = ""; create_user = ""; lm_time = ""; lm_user = ""; can_read = new bool(); } } public class FileInfoAndCondition { public FileInfoCondition condition { get; set; } public List<FileInfo> fileInfos { get; set; } public FileInfoAndCondition() { condition = new FileInfoCondition(); fileInfos = new List<FileInfo>(); } } /// <summary> /// 查询文件信息接口 /// </summary> public class FileInfoQuery { public string code { get; set; } public string message { get; set; } public FileInfoAndCondition datas { get; set; } public FileInfoQuery() { code = ""; message = ""; datas = new FileInfoAndCondition(); } } /// <summary> /// 文件信息 /// </summary> public class FileInfoData { public List<FileInfo> datas { get; set; } public FileInfoData() { datas = new List<FileInfo>(); } } public class QueryFileTrackArg { // 通讯令牌 public string secretKey { get; set; }//由token进过MD5->BASE64->MD5获得 // 任务令牌 public string token { get; set; }//客户端生成一个UUID // 文件编号 public string fileID { get; set; } // 操作用户编号 public string optUserID { get; set; } // 查询的版本编号 public string taskID { get; set; } public QueryFileTrackArg() { secretKey = ""; token = ""; fileID = ""; optUserID = ""; taskID = ""; } } public class FileTrack { // 文件操作 public string act_cmd { get; set; } // 是否可读 public bool can_read { get; set; } // 文件创建时间 public string create_time { get; set; } // 文件创建人 public string create_user { get; set; } // 是否删除 public bool is_del { get; set; } // 是否隐藏 public bool is_hide { get; set; } // 文件最后修改时间 public string lm_time { get; set; } // 文件最后修改人 public string lm_user { get; set; } // 文件大小 public int size { get; set; } public string taskID { get; set; } public FileTrack() { act_cmd = ""; can_read = new bool(); create_time = ""; create_user = ""; is_del = new bool(); is_hide = new bool(); lm_time = ""; lm_user = ""; size = new int(); taskID = ""; } } public class FileTrackCondition { public string fileID { get; set; } public string taskID { get; set; } public FileTrackCondition() { fileID = ""; taskID = ""; } } /// <summary> /// 查询文件轨迹接口 /// </summary> public class FileTrackQuery { public string code { get; set; } public string message { get; set; } public FileTrackCondition condition { get; set; } public List<FileTrack> datas { get; set; } public FileTrackQuery() { code = ""; message = ""; condition = new FileTrackCondition(); datas = new List<FileTrack>(); } } /// <summary> /// 文件轨迹 /// </summary> public class FileTrackData { public List<FileTrack> datas { get; set; } public FileTrackData() { datas = new List<FileTrack>(); } } /// <summary> /// 字典item /// </summary> public class DictionaryData { public string version { get; set; } public string task_time { get; set; } public DictionaryData() { version = ""; task_time = ""; } } public class FileRecoverArg { // 通讯令牌 public string secretKey { get; set; }//由token进过MD5->BASE64->MD5获得 // 任务令牌 public string token { get; set; }//客户端生成一个UUID // 操作用户编号 public string optUserID { get; set; } public string fileID { get; set; } public string taskID { get; set; } public string password { get; set; } public FileRecoverArg() { secretKey = ""; token = ""; optUserID = ""; fileID = ""; taskID = ""; password = ""; } } }

C# Linq 对long进行比较时出现异常

我在Core 3.1中使用MySql.Data.EntityFramework遇到了一个问题。 mysql中id的数据类型是bigint,我在写Entitiy时将它作为long处理: ``` [Column("article_id", TypeName = "bigint")] public long Id { get; set; } ``` 当我Get实体时,能够正常获取到它的id。之后我定义了一个方法 ArticleExistsAsync,希望根据传入的long类型id,判断该实体是否存在: ``` public async Task<bool> ArticleExistsAsync(long articleId) { return await _context.Articles.AnyAsync(x => x.Id==articleId); } ``` 但是在运行时抛出了如下异常 >InvalidOperationException: No coercion operator is defined between types 'System.Int16' and 'System.Boolean'. > System.Linq.Expressions.Expression.GetUserDefinedCoercionOrThrow(ExpressionType coercionType, Expression expression, Type convertToType) 目前没有头绪,希望各位dalao能提供一些解决思路,非常感谢。

我可以用php / nodejs与SignalR api交谈吗?

<div class="post-text" itemprop="text"> <p>so I'm a PHP and NODEJS programmer, I'm trying to talk to an API </p> <p>the company that provides the API told me they only have <code>c#</code> client and they gave me some c# code and documentation and a link ... I assumed it must be soap or rest API </p> <p>so I open the link and saw this error</p> <pre><code>Protocol error: Unknown transport. </code></pre> <p>so I searched the error and found out its related to <code>SignalR lib</code>, so it must be a <code>SignalR API</code> (I'm guessing ... if that's the right name for it )</p> <p>I also searched for <code>SignalR</code> in the code they gave me and saw this</p> <pre><code>namespace OMS.Business.Client { public abstract class SignalRClientProxyBase : IDisposable { protected HubConnection Connection { get; private set; } protected IHubProxy Hub { get; private set; } public string ServiceUrl { get; private set; } public string HubName { get; private set; } private Task _connectionTask; public string ServerName { get; private set; } public SignalRClientProxyBase(string serverUrl, string hubName, string serverName, bool autoReconnect, Dictionary&lt;string, string&gt; queryString = null) { ServiceUrl = serverUrl; HubName = hubName; ServerName = serverName; if (queryString != null) { Connection = new HubConnection(serverUrl, queryString); } else { Connection = new HubConnection(serverUrl); } if (autoReconnect) { Connection.StateChanged += _connection_StateChanged; } Hub = Connection.CreateHubProxy(hubName); InitHub(Hub); StartConnection(); try { Connection.Start().Wait(); } catch (Exception ex) { /*Nothing*/} } </code></pre> <p>which seems to be confirming my guess </p> <p>so my question is is it possible to talk to this API with PHP or should I give up? basically, I'm in the dark, the company doesn't provide any help .... any suggestion or pointers will be appreciated.</p> </div>

等待多个goroutines的结果

<div class="post-text" itemprop="text"> <p>I am searching a way to execute asynchronously two functions in go which returns different results and errors, wait for them to finish and print both results. Also if one of function returned error I do not want to wait for another function, and just print the error. For example, I have this functions:</p> <pre><code>func methodInt(error bool) (int, error) { &lt;-time.NewTimer(time.Millisecond * 100).C if error { return 0, errors.New("Some error") } else { return 1, nil } } func methodString(error bool) (string, error) { &lt;-time.NewTimer(time.Millisecond * 120).C if error { return "", errors.New("Some error") } else { return "Some result", nil } } </code></pre> <p>Here <a href="https://play.golang.org/p/-8StYapmlg" rel="nofollow noreferrer">https://play.golang.org/p/-8StYapmlg</a> is how I implemented it, but it has too much code I think. It can be simplified by using interface{} but I don't want to go this way. I want something simpler as, for example, can be implemented in C# with async/await. Probably there is some library that simplifies such operation.</p> <p>UPDATE: Thank for your responses! It is awesome how fast I got help! I like the usage of WaitGroup. It obviously makes the code more robust to changes, so I easily can add another async method without changing exact count of methods in the end. However, there is still so much code in comparison to same in C#. I know that in go I don't need to explicitly mark methods as async, making them actually to return tasks, but methods call looks much more simple, for example, consider this link <a href="https://stackoverflow.com/questions/25009437/running-multiple-async-tasks-and-waiting-for-them-all-to-complete">actually catching exception is also needed</a> By the way, I found that in my task I actually don't need to know returning type of the functions I want to run async because it will be anyway marshaled to json, and now I just call multiple services in the endpoint layer of go-kit.</p> </div>

测试http.Response.Body已关闭

<div class="post-text" itemprop="text"> <p>I'm searching for an easy way to test that http.Response.Body.Close() was called.</p> <p>I already tried this by counting the number of open connections to the server (<a href="https://golang.org/src/net/http/serve_test.go" rel="nofollow noreferrer">https://golang.org/src/net/http/serve_test.go</a> - countCloseListener), but it seems that it only is testable on the client side, via rewriting the Roundtripper.</p> <p>So the following example works, but I'm wondering whether there is an easier way for such a common task...</p> <pre><code>package closing import "net/http" type MyClient struct { Client http.Client } func (c *MyClient) Closing() (err error) { res, err := c.Client.Get("http://localhost") defer res.Body.Close() return } func (c *MyClient) NotClosing() (err error) { _, err = c.Client.Get("http://localhost") return } </code></pre> <p><a href="https://github.com/elgohr/golang-test-body-close/blob/master/performsHttpRequest.go" rel="nofollow noreferrer">https://github.com/elgohr/golang-test-body-close/blob/master/performsHttpRequest.go</a></p> <pre><code>package closing_test import ( "github.com/elgohr/closing" "io" "io/ioutil" "net/http" "strings" "testing" ) func TestShouldBeClosedWhenClosed(t *testing.T) { tripper := NewFakeRoundTripper() cl := closing.MyClient{ Client: http.Client{ Transport: tripper, }, } if err := cl.Closing(); err != nil { t.Error(err) } if !tripper.Body.Closed { t.Error("Should be closed, but wasn't") } } func TestShouldBeOpenWhenNotClosed(t *testing.T) { tripper := NewFakeRoundTripper() cl := closing.MyClient{ Client: http.Client{ Transport: tripper, }, } if err := cl.NotClosing(); err != nil { t.Error(err) } if tripper.Body.Closed { t.Error("Should be open, but wasn't") } } func NewFakeRoundTripper() *FakeRoundTripper { return &amp;FakeRoundTripper{ Body: &amp;FakeReadCloser{ ReadCloser: ioutil.NopCloser(strings.NewReader("content")), }, } } type FakeRoundTripper struct { Body *FakeReadCloser } func (r *FakeRoundTripper) RoundTrip(*http.Request) (*http.Response, error) { return &amp;http.Response{ Body: r.Body, }, nil } type FakeReadCloser struct { io.ReadCloser Closed bool } func (r *FakeReadCloser) Close() error { r.Closed = true return r.ReadCloser.Close() } </code></pre> <p><a href="https://github.com/elgohr/golang-test-body-close/blob/master/performsHttpRequest_test.go" rel="nofollow noreferrer">https://github.com/elgohr/golang-test-body-close/blob/master/performsHttpRequest_test.go</a></p> </div>

将图片从xamarin表单上传到php服务器

<div class="post-text" itemprop="text"> <p>Please I have been trying to upload pictures from a xamarin form application to a php server but seems not to be working. The server receives an empty $_FILES request. This is the c# code.</p> <pre><code> public async Task&lt;bool&gt; Upload(MediaFile mediaFile, string filename) { byte[] bitmapData; var stream = new MemoryStream(); mediaFile.GetStream().CopyTo(stream); bitmapData = stream.ToArray(); var fileContent = new ByteArrayContent(bitmapData); fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream"); fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "fileUpload", FileName = filename }; string boundary = "---8393774hhy37373773"; MultipartFormDataContent multipartContent = new MultipartFormDataContent(boundary); multipartContent.Add(fileContent); HttpClient httpClient = new HttpClient(); HttpResponseMessage response = await httpClient.PostAsync("http://www.url.com/upload.php", multipartContent); response.EnsureSuccessStatusCode(); if (response.IsSuccessStatusCode) { string content = await response.Content.ReadAsStringAsync(); return true; } return false; } </code></pre> <p>Below is the php file to receive the uploaded image. I tried to save the content of the posted image to file but the file only has an empty array and always return "failure". Please what am i missing wrong? I have searched the web but cant seem to understand the problem.</p> <pre><code> $uploads_dir = 'uploads/'; $req_dump = print_r( $_FILES, true ); $fp = file_put_contents( 'data.txt', $req_dump ); if (isset($_FILES["fileUpload"]["tmp_name"]) AND is_uploaded_file($_FILES["fileUpload"]["tmp_name"])) { $tmp_name = $_FILES["fileUpload"]["tmp_name"]; $name = $_FILES["fileUpload"]["name"]; $Result = move_uploaded_file($tmp_name, "$uploads_dir/$name"); echo "Success"; } else { echo "Failure"; } </code></pre> </div>

启动应用程序时,有没有办法以编程方式清除浏览器缓存?

<div class="post-text" itemprop="text"> <p>由于我对用C#编程(并在WPF中创建应用程序)相当陌生,所以我想寻求您的帮助。</p> <p>我们已经实现了我们称为“JobCacheUpdater”的东西。在不钻研太多细节的情况下,我们的基本想法如下:</p> <ul> <li>1、我们的数据库包含数千个具有不同信息位的项目。</li> <li>2、然后,我们希望异步地在我们的网站上加载这些信息(Ajax)。</li> <li>3、但是,我们不需要将这些信息单独地拼凑在一起,而是要将HTML-字符串呈现到数据库中的一个单独的表中。</li> <li>4、然后,我们根据一个ProjectID从该表中选择一行,该HTML-String基本上显示了包含项目所需信息的表。</li> </ul> <p>这个“JobCacheUpdater”定期运行,这样我们就可以将带有HTML字符串的表与所有项目的主表同步起来。</p> <p>到目前为止,我们已经使用Watin在后台运行浏览器、读取和呈现HTML-字符串,但我目前的任务是实现ChromiumEmbeddedFramework(CEF),而不是实现已有的功能。</p> <p>在示例WPF项目中编写基本代码非常容易,但是当我使用项目的一些随机URL读取该页面的源代码并将其写入.txt文件时,我注意到它只加载了网站的“骨架”(如果我可以这样称呼它),但没有加载包含必要信息的表。</p> <p>我编写了一个ChromeWrapper类,如下所示:</p> <pre><code>public class ChromeWrapper : IDisposable { private readonly ChromiumWebBrowser _browser; private string _html = ""; private bool _pageIsLoaded = false; public ChromeWrapper() { var settings = new CefSettings(); settings.CefCommandLineArgs.Add("disable-gpu", "1"); Cef.Initialize(settings, shutdownOnProcessExit: true, performDependencyCheck: true); _browser = new ChromiumWebBrowser(string.Empty); _browser.BrowserSettings.ApplicationCache = CefState.Disabled; } public string GetHtml(string url) { _pageIsLoaded = false; while (!_browser.IsBrowserInitialized) Thread.Sleep(100); _browser.Load(url); _browser.LoadingStateChanged += BrowserLoadingStateChanged; while (!_pageIsLoaded) Thread.Sleep(100); return _html; } private void BrowserLoadingStateChanged(object sender, LoadingStateChangedEventArgs e) { // Check to see if loading is complete - this event is called twice, one when loading starts // second time when it's finished // (rather than an iframe within the main frame). if (e.IsLoading) return; _browser.LoadingStateChanged -= BrowserLoadingStateChanged; var htmlTask = e.Browser.MainFrame.GetSourceAsync(); htmlTask.ContinueWith(obj =&gt; { _html = htmlTask.Result; _pageIsLoaded = true; }); } public void Dispose() { if (_browser != null) _browser.Dispose(); Cef.Shutdown(); } } </code></pre> <p>单击Button1后,我的MainWindows类实例化ChromeWrapper,然后将源保存到我的桌面上的.txt文件中:</p> <pre><code> private void Button1Click(object sender, RoutedEventArgs e) { using (var chrome = new ChromeWrapper()) { var html = chrome.GetHtml(@"URL Test"); var htmltPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "CefSharpTest2.html"); File.WriteAllText(htmltPath, html); Process.Start(htmltPath); chrome.Dispose(); } } </code></pre> <p>有趣的是,如果我在Button1Click中两次启动chrome.GetHtml,就会得到想要的结果,这使我得出结论,浏览器缓存可能有问题,但是我不是很确定。</p> <p>另一个问题:启动应用程序时,有没有办法以编程方式清除浏览器缓存?</p> <p>任何帮助都将不胜感激,谢谢!</p> </div>

尝试将图像(以字节[]形式发送)上传到PHP中的域文件夹/服务器

<div class="post-text" itemprop="text"> <p>With this current code when I send a byte [] (and the imagename) from my frontend I receive this echo in the log "upload failed". I have an existing folder on my domain named "photosFolder" where I try to store my image and its imagename that I send from the frontend.</p> <p>I am a bit confused now how to make this work so I added an move_uploaded_file that I frequently saw when I googled this issue. Is that the correct approach?</p> <p>This is the PHP-code that I currently have.</p> <pre><code>&lt;?php $input = file_get_contents('php://input'); $value = json_decode($input, true); if (!empty($value)) { file_put_contents($value['photo_name'], base64_decode($value['photo_data'])); $image_name = $value['photo_name']; $image_data = $value['photo_data']; if(move_uploaded_file($image_data, "photosFolder/$image_name")) { echo "image uploaded!"; } else { echo "upload failed"; } } ?&gt; </code></pre> <p>I send my byte [] like this from my frontend:</p> <pre><code>static public async Task&lt;bool&gt; createPhotoThree(string imgName, byte[] imgData) { var httpClientRequest = new HttpClient(); var postData = new Dictionary&lt;string, object&gt;(); postData.Add("photo_name", imgName); postData.Add("photo_data", imgData); var jsonRequest = JsonConvert.SerializeObject(postData); HttpContent content = new StringContent(jsonRequest, System.Text.Encoding.UTF8, "application/json"); var result = await httpClientRequest.PostAsync("http://myadress.com/test.php", content); var resultString = await result.Content.ReadAsStringAsync(); return true; } </code></pre> </div>

如何从PHP中的byte []获取image_name和image_tmp_name?

<div class="post-text" itemprop="text"> <p>I am currently sending an byte [] from my frontend into my domain and PHP-code. The byte array that I am sending is named "photo" and it is sent like a System.Text.Encoding.UTF8, "application/json". My goal is to get the byte [] into an image and then upload it my domainfolder (that already exists) do I need to get the image_name and the image_tmp_name from that byte [] in order to do this? I am a bit uncertain on how exactly I should get this to work.</p> <p>I currently have this code:</p> <pre><code>&lt;?php $value = json_decode(file_get_contents('php://input')); if(!empty($value)) { print_r($value); } ?&gt; </code></pre> <p>With this code the print gives me a huge line of text containing the byte []. </p> <p>How do I now get the image_name and image_tmp_name from this byte []? My goal is to upload the image on my domainmap (named photoFolder that already exists) with a code looking something like this:</p> <pre><code>$image_tmp_name = ""; //I currently do not have this value $image_name = ""; //I currently do not have this value if(move_uploaded_file($image_tmp_name, "photoFolder/$image_name")) { echo "image successfully uploaded"; } </code></pre> <p>How i send it:</p> <pre><code>static public async Task &lt;bool&gt; createPhotoThree (byte [] imgData) { var httpClientRequest = new HttpClient (); var postData = new Dictionary &lt;string, object&gt; (); postData.Add ("photo", imgData); var jsonRequest = JsonConvert.SerializeObject(postData); HttpContent content = new StringContent(jsonRequest, System.Text.Encoding.UTF8, "application/json"); var result = await httpClientRequest.PostAsync("http://myadress.com/test.php", content); var resultString = await result.Content.ReadAsStringAsync (); return true; } </code></pre> </div>

Gorilla Websocket没有收到消息

<div class="post-text" itemprop="text"> <p>I am building a gateway in Golang that communicates with Gorilla websockets.</p> <p>I am running it on Ubuntu 16.04, and testing it currently with a .NET console app.</p> <p>Using Wireshark on Windows and sniffit on Ubuntu have determined that <em>messages are being sent correctly from the Windows client and received by the Ubuntu box</em>.</p> <p>In my code, however, sometimes after a few successful messages, and sometimes after none, my gateway is failing to read the message (still sitting at <code>_, msg, errCon := conn.ReadMessage()</code>)</p> <p>An example of the output will be:</p> <blockquote> <p>2018/03/27 02:38:06 Awaiting Message ... 2018/03/27 02:38:07 Message received: main.AdminRequest{Data:"{\"SomeDataHeader\":\"SomeData\"}", Requestor:"user", Type:"JustDoSomethingRequest", Ukey:"talca"} 2018/03/27 02:38:07 {"SomeDataHeader":"SomeData"} 2018/03/27 02:38:07 Awaiting Message ...</p> </blockquote> <p>As I have previously said, it may receive a few messages like this, but, despite network traffic on both ends continuing, no more messages will be received</p> <p>I am fairly new with Golang, and working under the assumption that I am missing something.</p> <p><strike>I have trimmed out error handling and the like for the sake of brevity in the code below, but this is an example of the failing code.</strike></p> <p><strong>EDIT</strong> As requested I have added Golang full code, and C# client code below (although, as I stated, Wireshark and sniffit have determined that data is going over the wire)</p> <pre><code>package main import ( "fmt" "net/http" "github.com/gorilla/websocket" "encoding/json" "log" ) var upgrader = websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, CheckOrigin: func(r *http.Request) bool { return true }, } type AdminRequest struct { Data string `json:"Data"` Requestor string `json:"Requestor"` Type string `json:"Type"` Ukey string `json:"Ukey"` } func main() { http.HandleFunc("/a", func(w http.ResponseWriter, r *http.Request) { var conn, _ = upgrader.Upgrade(w, r, nil) go func(conn *websocket.Conn) { for { _, _, err := conn.ReadMessage() if err != nil { log.Println("Close: "+ err.Error()) conn.Close() return } } }(conn) go func(conn *websocket.Conn) { for { log.Println("Awaiting Message ...") _, msg, errCon := conn.ReadMessage() if errCon != nil { log.Println("Read Error:", errCon) break } log.Println("Message received: ") var r AdminRequest if err := json.Unmarshal(msg, &amp;r); err != nil { log.Println("Error: " + err.Error()); return; } fmt.Printf("%#v ", r) log.Println(r.Data); } }(conn) }) http.ListenAndServe(":3000", nil) } </code></pre> <p>C# Code:</p> <pre><code>public class Client : IDisposable { private ClientWebSocket _socket; string _address; int _port; public Client(string address) { _address = address; _socket = new ClientWebSocket(); } public async void SetupForReceivingStuffs() { while (_socket.State == WebSocketState.Open) { ArraySegment&lt;byte&gt; receivedBytes = new ArraySegment&lt;byte&gt;(new byte[1024]); WebSocketReceiveResult result = await _socket.ReceiveAsync(receivedBytes, CancellationToken.None); Console.WriteLine(Encoding.UTF8.GetString(receivedBytes.Array, 0, result.Count)); } } public async void SetupForSendingStuffs(ConcurrentQueue&lt;AdminRequest&gt; queue) { while (_socket.State == WebSocketState.Open) { AdminRequest next; while (queue.Count &gt; 0) { if (queue.TryDequeue(out next)) { await Send(next); } } await Task.Yield(); } } public async Task Connect() { while (_socket.State != WebSocketState.Open) { try { _socket = new ClientWebSocket(); await _socket.ConnectAsync(new Uri(_address), CancellationToken.None); Console.WriteLine("Socket state: " + _socket.State); } catch (Exception ex) { //Not getting hit Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); } } } public Task Send&lt;TData&gt;(TData data) { string text = JsonConvert.SerializeObject(data); var encoded = Encoding.UTF8.GetBytes(text); var buffer = new ArraySegment&lt;Byte&gt;(encoded, 0, encoded.Length); return _socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None); } public void Dispose() { _socket.Dispose(); } } </code></pre> <p>Called by:</p> <pre><code>class Program { static ConcurrentQueue&lt;AdminRequest&gt; _toSend; static void Main(string[] args) { _toSend = new ConcurrentQueue&lt;AdminRequest&gt;(); Client client = new Client("ws:/(myip):(myport)/a"); client.Connect().Wait(); //client.SetupForReceivingStuffs(); client.SetupForSendingStuffs(_toSend); WriteInstructions(); LoopAuto(); Console.WriteLine("Bye"); } private static void LoopAuto() { DateTime nextMessage = DateTime.Now; while (true) { if (DateTime.Now &lt; nextMessage) continue; Console.WriteLine("Next"); nextMessage = DateTime.Now.AddSeconds(2); _toSend.Enqueue(new AdminRequest { Data = "{\"SomeDataHeader\":\"SomeData\"}", Requestor = "user", Type = "JustDoSomethingRequest", Ukey = "talca" }); } } private static ConsoleKeyInfo LoopManual() { ConsoleKeyInfo info; do { info = Console.ReadKey(true); if (info.KeyChar == '1') { _toSend.Enqueue(new AdminRequest { Data = "{\"SomeDataHeader\":\"SomeData\"}", Requestor = "user", Type = "JustDoSomethingRequest", Ukey = "talca" }); } else if (info.KeyChar == 'i') { WriteInstructions(); } } while (info.KeyChar != 'x'); return info; } private static void WriteInstructions() { Console.WriteLine("1. Send New Message"); Console.WriteLine("i. Instructions (these lines)"); Console.WriteLine("x: Exit"); } } </code></pre> </div>

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

再不跳槽,应届毕业生拿的都比我多了!

跳槽几乎是每个人职业生涯的一部分,很多HR说“三年两跳”已经是一个跳槽频繁与否的阈值了,可为什么市面上有很多程序员不到一年就跳槽呢?他们不担心影响履历吗? PayScale之前发布的**《员工最短任期公司排行榜》中,两家码农大厂Amazon和Google**,以1年和1.1年的员工任期中位数分列第二、第四名。 PayScale:员工最短任期公司排行榜 意外的是,任期中位数极小的这两家公司,薪资...

我以为我学懂了数据结构,直到看了这个导图才发现,我错了

数据结构与算法思维导图

数据库——玩转SQL语句(以MySQL为例)

一、前言 照着大学的SQL server来学

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

华为初面+综合面试(Java技术面)附上面试题

华为面试整体流程大致分为笔试,性格测试,面试,综合面试,回学校等结果。笔试来说,华为的难度较中等,选择题难度和网易腾讯差不多。最后的代码题,相比下来就简单很多,一共3道题目,前2题很容易就AC,题目已经记不太清楚,不过难度确实不大。最后一题最后提交的代码过了75%的样例,一直没有发现剩下的25%可能存在什么坑。 笔试部分太久远,我就不怎么回忆了。直接将面试。 面试 如果说腾讯的面试是挥金如土...

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

讲一个程序员如何副业月赚三万的真实故事

loonggg读完需要3分钟速读仅需 1 分钟大家好,我是你们的校长。我之前讲过,这年头,只要肯动脑,肯行动,程序员凭借自己的技术,赚钱的方式还是有很多种的。仅仅靠在公司出卖自己的劳动时...

上班一个月,后悔当初着急入职的选择了

最近有个老铁,告诉我说,上班一个月,后悔当初着急入职现在公司了。他之前在美图做手机研发,今年美图那边今年也有一波组织优化调整,他是其中一个,在协商离职后,当时捉急找工作上班,因为有房贷供着,不能没有收入来源。所以匆忙选了一家公司,实际上是一个大型外包公司,主要派遣给其他手机厂商做外包项目。**当时承诺待遇还不错,所以就立马入职去上班了。但是后面入职后,发现薪酬待遇这块并不是HR所说那样,那个HR自...

总结了 150 余个神奇网站,你不来瞅瞅吗?

原博客再更新,可能就没了,之后将持续更新本篇博客。

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

程序员写出这样的代码,能不挨骂吗?

当你换槽填坑时,面对一个新的环境。能够快速熟练,上手实现业务需求是关键。但是,哪些因素会影响你快速上手呢?是原有代码写的不够好?还是注释写的不够好?昨夜...

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

HTTP与HTTPS的区别

面试官问HTTP与HTTPS的区别,我这样回答让他竖起大拇指!

程序员毕业去大公司好还是小公司好?

虽然大公司并不是人人都能进,但我仍建议还未毕业的同学,尽力地通过校招向大公司挤,但凡挤进去,你这一生会容易很多。 大公司哪里好?没能进大公司怎么办?答案都在这里了,记得帮我点赞哦。 目录: 技术氛围 内部晋升与跳槽 啥也没学会,公司倒闭了? 不同的人脉圈,注定会有不同的结果 没能去大厂怎么办? 一、技术氛围 纵观整个程序员技术领域,哪个在行业有所名气的大牛,不是在大厂? 而且众所...

程序员为什么千万不要瞎努力?

本文作者用对比非常鲜明的两个开发团队的故事,讲解了敏捷开发之道 —— 如果你的团队缺乏统一标准的环境,那么即使勤劳努力,不仅会极其耗时而且成果甚微,使用...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

终于懂了TCP和UDP协议区别

终于懂了TCP和UDP协议区别

无代码时代来临,程序员如何保住饭碗?

编程语言层出不穷,从最初的机器语言到如今2500种以上的高级语言,程序员们大呼“学到头秃”。程序员一边面临编程语言不断推陈出新,一边面临由于许多代码已存在,程序员编写新应用程序时存在重复“搬砖”的现象。 无代码/低代码编程应运而生。无代码/低代码是一种创建应用的方法,它可以让开发者使用最少的编码知识来快速开发应用程序。开发者通过图形界面中,可视化建模来组装和配置应用程序。这样一来,开发者直...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

《Oracle Java SE编程自学与面试指南》最佳学习路线图(2020最新版)

01、Java入门(Getting Started);02、集成开发环境(IDE);03、项目结构(Eclipse JavaProject);04、类和对象(Classes and Objects);05:词法结构(Lexical Structure);06:数据类型和变量(Data Type and Variables);07:运算符(Operators);08:控制流程语句(Control Flow Statements);

Java岗开发3年,公司临时抽查算法,离职后这几题我记一辈子

前几天我们公司做了一件蠢事,非常非常愚蠢的事情。我原以为从学校出来之后,除了找工作有测试外,不会有任何与考试有关的事儿。 但是,天有不测风云,公司技术总监、人事总监两位大佬突然降临到我们事业线,叫上我老大,给我们组织了一场别开生面的“考试”。 那是一个风和日丽的下午,我翘着二郎腿,左手端着一杯卡布奇诺,右手抓着我的罗技鼠标,滚动着轮轴,穿梭在头条热点之间。 “淡黄的长裙~蓬松的头发...

大牛都会用的IDEA调试技巧!!!

导读 前天面试了一个985高校的实习生,问了他平时用什么开发工具,他想也没想的说IDEA,于是我抛砖引玉的问了一下IDEA的调试用过吧,你说说怎么设置断点...

面试官:你连SSO都不懂,就别来面试了

大厂竟然要考我SSO,卧槽。

终于,月薪过5万了!

来看几个问题想不想月薪超过5万?想不想进入公司架构组?想不想成为项目组的负责人?想不想成为spring的高手,超越99%的对手?那么本文内容是你必须要掌握的。本文主要详解bean的生命...

我说我懂多线程,面试官立马给我发了offer

不小心拿了几个offer,有点烦

立即提问
相关内容推荐