c#简单模拟商品秒杀

 主函数:

    class Program
    {
        public static List<Thread> threads = new List<Thread>();
        public static int count = 0;
        public static List<P> plist = new List<P>();
        static void Main(string[] args)
        {     
            //数据生成
            //for (int i = 0; i < 10; i++)
            //{
            //    plist.Add(new P() { id = i, name = "p" + i, count = ((i + 1) * 10) });
            //    RedisHelper.SetEntryInHash("p", "p" + i, ((i + 1) * 10).ToString());
            //}

            //创建模拟线程
            for (int i = 0; i < 11; i++)
            {
                Thread thread = new Thread(SecKill);
                thread.IsBackground = true;
                thread.Start(i);
            }
            Console.ReadKey();
        }

线程调用函数 

public static void SecKill(object obj) {
            bool issuccess = false;
            int indexthread = (int)obj;
            if (plist.Count == 0)
            {
               
               Dictionary<string, string> keyValuePairs = RedisHelper.GetAllEntriesFromHash("p");
               foreach (var item in keyValuePairs.Keys)
               {
                   P p = new P() { id = Convert.ToInt32(item.Remove(0, 1)), count = Convert.ToInt32(keyValuePairs[item]), name = item };
                   p.isSure = p.count > 0;
                   plist.Add(p);
               }
            }
            for (int i = 0; i < 1; i++)
            {

                // RedisHelper.SetEntryInHash("p", "p" + i, ((i + 1) * 10).ToString());//redis键名称,字典(字典键,字典值)
                issuccess = RedisHelper.SecKill(i, ref plist);
                Console.WriteLine(string.Format("indexthread:"+ indexthread+"号线程:" + i + ":" + (issuccess ? "抢到了!!!!!" : "没用抢到!!!!!!!")));
            }

        }

  servcestack.redis3.9.7,帮助类

using ServiceStack.Common;
using ServiceStack.Redis;
using ServiceStack.Text;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace CsharpTest
{
    //servcestack.redis3.9.7
    public class RedisHelper
    {
        private readonly static string RedisPath = "123654@127.0.0.1:6379";
        private readonly static PooledRedisClientManager _pool = null;
        public static IRedisClient redisClient = null;
        static RedisHelper()
        {
            if (redisClient == null)
            {
                _pool = new PooledRedisClientManager(new string[] { RedisPath }, new string[] { RedisPath }, new RedisClientManagerConfig() { MaxReadPoolSize = 50, MaxWritePoolSize = 50, AutoStart = true });
                //redisClient = _pool.GetClient();
            }
        }    
              //修改hash的值
public static long IncrementValueInHash(string hashId, string key, int incrementBy) {
            long count = 0;
            using (IRedisClient r = _pool.GetClient()) {
                count=r.IncrementValueInHash(hashId, key, incrementBy);
            }
            return count;
        }
//设置hash表
        public static bool SetEntryInHash(string hashId, string key, string value) {
            bool issuccess = false;
            using (IRedisClient r = _pool.GetClient())
            {
                issuccess = r.SetEntryInHash(hashId, key, value);
            }
            return issuccess;

        }
        /// <summary>
        /// 模拟秒杀
        /// </summary>
        /// <returns></returns>
        public static bool SecKill(int i,ref List<P> ps) {
            bool issuccess = false;
            using (IRedisClient r = _pool.GetClient())
            {
                using (IDisposable d=r.AcquireLock("lock"))
                {
                    try
                    {
                        if (ps[i].isSure)
                        {
                            ps[i].isSure = r.IncrementValueInHash("p", ps[i].name, -1) > 0;
                            issuccess = true;
                        }
                        else
                        {
                            issuccess = false;
                        }
                    }
                    catch (Exception ex)
                    {
                        d.Dispose();
                    }
                    finally { 
                    
                    }
                }
            }
            return issuccess;
        }

        public static Dictionary<string, string> GetAllEntriesFromHash(string hashId) {
            Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
            using (IRedisClient r = _pool.GetClient())
            {
                keyValuePairs= r.GetAllEntriesFromHash(hashId);
            }
            return keyValuePairs;
        }
    }
}

模拟类

    public class P
    {
        public int id { get; set; }
        public string name { get; set; }
        public bool isSure { get; set; }
        public int count { get; set; }
    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是C#模拟鼠标单击的示例代码: ```csharp using System; using System.Runtime.InteropServices; public class MouseSimulator { [DllImport("user32.dll", SetLastError = true)] static extern uint SendInput(uint nInputs, INPUT[] pInputs, int cbSize); [StructLayout(LayoutKind.Sequential)] struct INPUT { public uint type; public MOUSEINPUT mi; } [StructLayout(LayoutKind.Sequential)] struct MOUSEINPUT { public int dx; public int dy; public uint mouseData; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; } const uint MOUSEEVENTF_LEFTDOWN = 0x0002; const uint MOUSEEVENTF_LEFTUP = 0x0004; public static void SimulateLeftClick(int x, int y) { INPUT[] inputs = new INPUT[2]; inputs[0].type = 0; // INPUT_MOUSE inputs[0].mi.dx = x; inputs[0].mi.dy = y; inputs[0].mi.mouseData = 0; inputs[0].mi.dwFlags = MOUSEEVENTF_LEFTDOWN; inputs[0].mi.time = 0; inputs[0].mi.dwExtraInfo = IntPtr.Zero; inputs[1].type = 0; // INPUT_MOUSE inputs[1].mi.dx = x; inputs[1].mi.dy = y; inputs[1].mi.mouseData = 0; inputs[1].mi.dwFlags = MOUSEEVENTF_LEFTUP; inputs[1].mi.time = 0; inputs[1].mi.dwExtraInfo = IntPtr.Zero; SendInput(2, inputs, Marshal.SizeOf(typeof(INPUT))); } } ``` 上述代码中,我们使用了Windows API中的SendInput函数来模拟鼠标单击事件。具体来说,我们定义了一个MOUSEINPUT结构体来描述鼠标事件的各个参数,然后将其封装在一个INPUT结构体中,最后调用SendInput函数来发送模拟的鼠标事件。 要模拟鼠标单击,我们需要调用两次SendInput函数,第一次发送鼠标按下事件,第二次发送鼠标释放事件。在这个示例代码中,我们将这两个事件封装在了SimulateLeftClick函数中,该函数接受鼠标单击的坐标作为参数。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值