Beispiel #1
1
        static void Main(string[] args)
        {
            try
            {
                // Display a message to show we're in Main().
                Console.WriteLine("Starting the program.");

                // Get the number of milliseconds from the arguments
                // passed in from the command line.
                int milliseconds = GetMilliseconds(args[0]);

                // Create the ComplicatedCalculator object.
                ComplicatedCalculator cc =
                    new ComplicatedCalculator(milliseconds);

                // Create the delegate object.
                DoSomething method = new DoSomething(cc.CalculateValue);

                // Call the delegate asynchronously.
                IAsyncResult asynchStatus =
                    method.BeginInvoke(10.4, 7.451, null, null);

                // Call WaitOne() to wait until the async task is done.
                Console.WriteLine("\nWaiting for task to complete.");
                // Include a timeout and check to see if it completed in time.
                bool inTimeBool = asynchStatus.AsyncWaitHandle.WaitOne(10000);
                if (inTimeBool)
                {
                    Console.WriteLine("\nTask has completed.");

                    // Get the result of the asynchronous call.
                    double results = method.EndInvoke(asynchStatus);

                    // Display the results.
                    Console.WriteLine("\nThe result is: {0}", results);
                }
                else
                {
                    Console.WriteLine("\nTask did NOT complete in time. There are no results. May need to stop application running using Task Manager.");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("\nEXCEPTION: {0}.", e.Message);
            }

            // Pause so we can look at the console window.
            Console.Write("\n\nPress <ENTER> to end: ");
            Console.ReadLine();
        }
Beispiel #2
0
        public string execute()
        {
            this.doer  = new DoSomething();
            tmplString = doer.justdoit();

            return(doExecute(tmplString));
        }
Beispiel #3
0
        static void Main(string[] args)
        {
            Console.WriteLine("这是主线程 ID:" + Thread.CurrentThread.ManagedThreadId);
            //无参无返回值
            DoSomething doSomething = Method1;

            doSomething.BeginInvoke(null, null);

            //无参有返回值
            DoSomethingReturn doSomethingReturn = Method2;
            IAsyncResult      iasyncResult      = doSomethingReturn.BeginInvoke(null, null);
            int result = doSomethingReturn.EndInvoke(iasyncResult);//要获取委托的返回值,必须等待子线程执行结束

            //有参无返回值
            DoMore doMore = Method3;

            doMore.BeginInvoke(16, "guo", null, null);

            //有参有返回值
            DoMoreReturn doMoreReturn  = Method4;
            IAsyncResult iasyncResult2 = doMoreReturn.BeginInvoke(16, "guo", null, null);
            int          result2       = doMoreReturn.EndInvoke(iasyncResult2);//要获取委托的返回值,必须等待子线程执行结束

            //异步回调
            DoMoreReturn doMoreReturn2 = Method4;

            doMoreReturn2.BeginInvoke(16, "guo", Callback, "wulala");
            Console.ReadKey();
        }
Beispiel #4
0
        /// <summary>
        /// 具体业务操作
        /// </summary>
        /// <param name="doMethod"></param>
        protected void Do(DoSomething doMethod)
        {
            // 由于长时间操作,需要启动新线程异步执行,系统直接向下执行
            Thread t = new Thread(new ParameterizedThreadStart(this.BaseDo));

            t.Start(doMethod);
        }
    public static void  Main(System.String[] args)
    {
        DoSomething ds = new DoSomething();

        ds.Apple = "pie";
        // do something
    }
        static void Main(string[] args)
        {
            var thomas = new Person("Thomas", new List <int> {
                1, 4
            });

            // simple delegate
            DoSomething doSomething = new DoSomething(thomas.WithdrawalMoney);
            var         result      = doSomething(1);

            System.Console.WriteLine($"Do something and get the result: {result}");

            // events
            thomas.Shout                += Thomas_Shout;
            thomas.NeedBankSupport      += Thomas_NeedBankSupport;
            thomas.NeedBankSubscription += Thomas_NeedBankSubscription;

            // shout event
            thomas.Poke();
            thomas.Poke();
            thomas.Poke();
            thomas.Poke();

            // need bank support event
            thomas.WithdrawalMoney(1);
            thomas.WithdrawalMoney(1);
            thomas.WithdrawalMoney(1);
            thomas.WithdrawalMoney(1);

            // need bank subscription event
            thomas.WithdrawalMoney(5);
        }
        public IActionResult Browse(List <IFormFile> files)
        {
            DoSomething ds = new DoSomething();
            var         uploadedFileStream = files.First().OpenReadStream();

            return(ds.ParseMyStuff(uploadedFileStream));
        }
Beispiel #8
0
        public async Task ShouldRegisterAndUnregisterPeer()
        {
            var subscription1 = Subscription.Matching <DatabaseStatus>(status => status.DatacenterName == "Paris" && status.Status == "Ko");
            var subscription2 = Subscription.Any <DoSomething>();

            var bytes = _container.GetInstance <IMessageSerializer>().Serialize(subscription1);
            var json  = Encoding.UTF8.GetString(bytes);

            var obj = _container.GetInstance <IMessageSerializer>().Deserialize(bytes, typeof(Subscription));

            var command = new DoSomething();

            Assert.AreEqual(0, GlobalTestContext.Get());

            _bus.Start();

            await _bus.Subscribe(new SubscriptionRequest(subscription1));

            var peers = _directoryRepository.GetPeers(true);

            Assert.AreEqual(1, peers.Count());
            Assert.AreEqual(5, peers.First().Subscriptions.Count());

            await _bus.Subscribe(new SubscriptionRequest(subscription2));

            peers = _directoryRepository.GetPeers(true);
            Assert.AreEqual(1, peers.Count());
            Assert.AreEqual(6, peers.First().Subscriptions.Count());

            await _bus.Send(command);

            await Task.Delay(50);

            Assert.AreEqual(1, GlobalTestContext.Get());
        }
Beispiel #9
0
        private void btnAsnyc_Click(object sender, EventArgs e)
        {
            //实例化一个委托
            //DoSomething dosomething = new DoSomething(t => Console.WriteLine("这里是异步调用,str是{0}",t));
            //DoSomething dosomething =t => Console.WriteLine("这里是btnAsnyc_Click,str是{0},当前线程Id:{1}", t,Thread.CurrentThread.ManagedThreadId);
            //dosomething("直接调用");//主线程调用
            //dosomething.Invoke("Invoke调用");//主线程调用
            //dosomething.BeginInvoke("BeginInvoke调用", null, null);//这就是异步调用  子线程在调用

            Console.WriteLine("**************btnAsnyc_Click异步开始******************");
            DoSomething todo = DoSomethingTest;

            for (int i = 0; i < 5; i++)
            {
                todo.BeginInvoke(string.Format("btnAsnyc_Click异步"), null, null);//BeginInvoke  该方法就是一个异步执行的方法,会调用一个子线程
            }
            Console.WriteLine("**************btnAsnyc_Click异步结束******************");

            /***************总结异步的特点*******************
             * 1.同步会卡住界面,异步不会;原因:异步启动了子线程,主线程得到释放;
             * 2.同步方法会慢,异步方法会快,但是消耗的资源比较多,因为启动了多个子线程;
             * 3.异步线程启动是无序的,结束也是无序的,由操作系统决定;
             *
             *****************总结异步的特点***********/
        }
        public void TestExecute()
        {
            var doSomething = new DoSomething();
            var returnString = doSomething.Execute("asdf");

            Assert.AreEqual("asdf", returnString);
        }
Beispiel #11
0
    public void UndoItem()
    {
        DoSomething something = myDelegates[myDelegates.Count - 1];

        something.Invoke();
        myDelegates.RemoveAt(myDelegates.Count - 1);
    }
Beispiel #12
0
        public static void TryToDoDelegate()
        {
            DoSomething something = new DoSomething(DelegateEvent.DoSomething1);

            something += DelegateEvent.DoSomething2;
            something();
        }
Beispiel #13
0
        static void Main(string[] args)
        {
            //1.实例化一个委托,调用者发送一个请求,请求执行该方法体(还未执行)
            DoSomething doSomething = new DoSomething(
                () =>
            {
                Console.WriteLine("如果委托使用 beginInvoke 的话,这里便是异步方法体");
                //4,实现完这个方法体后自动触发下面的回调函数方法体
            }
                );

            //3 。调用者(主线程)去触发异步调用,采用异步的方式请求上面的方法体
            IAsyncResult result = doSomething.BeginInvoke(
                //2.自定义上面方法体执行后的回调函数
                new AsyncCallback
                (
                    //5.以下是回调函数方法体
                    //asyncResult.AsyncState其实就是AsyncCallback委托中的第二个参数
                    asyncResult =>
            {
                doSomething.EndInvoke(asyncResult);
                Console.WriteLine(asyncResult.AsyncState.ToString());
            }
                ),
                "AsyncResult.AsyncState"
                );

            //DoSomething......调用者(主线程)会去做自己的事情
            Console.ReadKey();
        }
Beispiel #14
0
        private void ShowResult(ref double myvalue, DoSomething MyMethod)
        {
            // Perform the action on the data.
            MyMethod(ref myvalue);

            // Display the data
            MessageBox.Show(myvalue.ToString());
        }
Beispiel #15
0
 public void Debug(string value)
 {
     if (null != Config.MainForm && Config.LocalSetting.NeedDebug)
     {
         DoSomething doSth = WriteText;
         Config.MainForm.InfoPage.Invoke(doSth, new object[] { DateTime.Now.ToString() + ":" + value + "\n" });
     }
 }
Beispiel #16
0
 /// <summary>
 ///     信息窗口显示信息
 /// </summary>
 /// <param name="value"></param>
 public void WriteLine(string value)
 {
     if (Config.MainForm != null)
     {
         DoSomething doSth = WriteText;
         Config.MainForm.InfoPage.Invoke(doSth, new object[] { DateTime.Now.ToString() + ":" + value + "\n" });
     }
 }
        public static void Demonstrate()
        {
            DoSomething dele  = new DoSomething(RunHere);
            DoSomething dele2 = RunHere;
            double      res1  = dele(2, 2.55);
            double      res2  = dele2(99, 9.25);

            System.Console.WriteLine($"res1:{res1},res2:{res2}");
        }
Beispiel #18
0
        protected virtual void OnDoing(string str)
        {
            DoSomething handler = (DoSomething)Events[EVENT_DOING];

            if (handler != null)
            {
                handler(str);
            }
        }
 static void Main(string[] args)
 {
     DoSomething print = new DoSomething(PrintLine);
     print += PauseTime;
     for (int i = 0; i < 100; i++)
     {
         print();
     }
 }
    public static int Helper(string socketPath)
    {
        DoSomething self = new DoSomething();

        Remoting.Publish(socketPath, self);

        Thread.Sleep(Timeout.Infinite);
        return(0);
    }
Beispiel #21
0
 public DurableFunction(
     IPipe pipe,
     ActivityLogger activityLogger,
     DoSomething doSomething)
 {
     _pipe           = pipe;
     _activityLogger = activityLogger;
     _doSomething    = doSomething;
 }
Beispiel #22
0
 public void Work()
 {
     //Works fine
     ((Action)DoSomething).RunAsThread();
     //Works fine
     Extensions.RunAsThread(DoSomething);
     //But I really need this to work
     DoSomething.RunAsThread();
 }
Beispiel #23
0
        public static void With <T>(this Control item, string id, DoSomething <T> fn) where T : class
        {
            var o = item.FindControl(id) as T;

            if (o != null && fn != null)
            {
                fn(o);
            }
        }
        static void Main(string[] args)
        {
            DoSomething d1 = new DoSomething(W);

            d1(new C());

            DoSomethingRet d2 = new DoSomethingRet(T);

            A a = d2(new C());
        }
Beispiel #25
0
        public void Bejaras(DoSomething operation)//valamit csinál vele bejárás során
        {
            ListaElem p = fej;

            while (p != null)
            {
                operation(p.tartalom);
                p = p.kovetkezo;
            }
        }
Beispiel #26
0
        public SplashViewModel(DoSomething doSomething)
        {
#if !Desktop
            var Scope = Startup.Instance.provider.CreateScope();
            _validationService = Scope.ServiceProvider.GetRequiredService <IValidationService>();
#endif
            // _validationService = new addon365.WebClient.Service.WebService.ValidationService();
            InvokeCaller = doSomething;
            RetryCommand = new RelayCommand(() => InvokeCaller());
        }
Beispiel #27
0
        public static void Main(string[] args)
        {
            //Safe efficient code enhancements
            var result = new DoSomething().Sum(15.15);

            //Conditional ref expressions
            int[] array  = { 1, 1, 2, 3 };
            int[] array2 = { 4, 5 };

            ref var ar = ref (array != null ? ref array[0] : ref array2[0]);
    static void Main(string[] args)
    {
        DoSomething print = new DoSomething(PrintLine);

        print += PauseTime;
        for (int i = 0; i < 100; i++)
        {
            print();
        }
    }
Beispiel #29
0
        static void Main(string[] args)
        {
            var work = new DoSomething();

            //immediately runs in a separate thread
            var process1Task = Task.Run(() => work.Process1());

            //immediately runs in a separate thread
            var process2Task = Task.FromResult(work.Process2());

            //blocks until it's done due to the 'Result' keyword
            Console.WriteLine($"Status: {process2Task.Result}");

            //let's kick off process3 immediately
            var process3Task = _process3Async(work);

            //and wait for it (meanwhile process 1 is still going likely)
            var process3TaskResult = process3Task.Result;

            Console.WriteLine($"Process3: {process3TaskResult}");

            //if we don't wait, the main thread will exit before Process1 is complete.
            //we'll never risk this with Process2 since we block until it's done
            process1Task.Wait();

            Console.WriteLine("All tasks complete!");

            Console.ReadKey();

            //now let's run three tasks but wait for them all to complete
            //they will end in reverse order
            Task.WaitAll(new Task[]
            {
                work.Process3Async(3000),
                work.Process3Async(2000),
                work.Process3Async(1000)
            });

            Console.WriteLine("All tasks complete!");

            Console.ReadKey();

            //now let's run three tasks but wait for ONLY ONE of them to complete
            //they will end in reverse order
            Task.WaitAny(new Task[]
            {
                work.Process3Async(3000),
                work.Process3Async(2000),
                work.Process3Async(1000)
            });

            Console.WriteLine("One task complete!");

            Console.ReadKey();
        }
        public void SimulateNotFound()
        {
            var client = ReplayHandler.GetClient(SimulateCallNotFound());

            var sut = new DoSomething(client, 42);

            sut.Run(new DoSomething.Parameters()
            {
                Type = "error"
            });
        }
Beispiel #31
0
        public static void print_02()
        {
            DoSomething DoIt = () =>
            {
                WriteLine("무언가를 해서");
                WriteLine("출력해보자");
                WriteLine("문형 람다식을 이용하여 이렇게!!");
            };

            DoIt();
        }
Beispiel #32
0
        public static void Main(string[] args)
        {
            A someA = new A();

            DoSomething something = WorkB;

            someA = something();

            Console.WriteLine("The value is " + someA.value);

            Console.ReadLine();
        }
    static async Task AsyncMain()
    {
        Console.Title = "Samples.SenderSideScaleOut.AwareClient";
        var endpointConfiguration = new EndpointConfiguration("Samples.SenderSideScaleOut.AwareClient");
        endpointConfiguration.UsePersistence<InMemoryPersistence>();
        endpointConfiguration.SendFailedMessagesTo("error");

        #region Logical-Routing

        var routing = endpointConfiguration.UnicastRouting();
        routing.RouteToEndpoint(typeof(DoSomething), "Samples.SenderSideScaleOut.Server");

        #endregion

        #region File-Based-Routing

        var transport = endpointConfiguration.UseTransport<MsmqTransport>();
        transport.DistributeMessagesUsingFileBasedEndpointInstanceMapping("routes.xml");

        #endregion

        var endpointInstance = await Endpoint.Start(endpointConfiguration)
            .ConfigureAwait(false);
        Console.WriteLine("Press enter to send a message");
        Console.WriteLine("Press any key to exit");

        var sequenceId = 0;
        while (true)
        {
            var key = Console.ReadKey();
            if (key.Key != ConsoleKey.Enter)
            {
                break;
            }
            var command = new DoSomething { SequenceId = ++sequenceId };
            await endpointInstance.Send(command)
                .ConfigureAwait(false);
            Console.WriteLine($"Message {command.SequenceId} Sent");
        }
        await endpointInstance.Stop()
            .ConfigureAwait(false);
    }
Beispiel #34
0
 public void AddMethod(Action act)
 {
     hasMethods = true;
     doSomething += new DoSomething(act);
 }
Beispiel #35
0
        static void Main(string[] args)
        {
            try
            {
                // Display a message to show we're in Main().
                Console.WriteLine("Starting the program.");

                // Get the number of milliseconds from the arguments
                // passed in from the command line.
                int milliseconds = GetMilliseconds(args[0]);

                // Create the ComplicatedCalculator object.
                ComplicatedCalculator cc =
                    new ComplicatedCalculator(milliseconds);

                // Create the delegate object.
                DoSomething method = new DoSomething(cc.CalculateValue);

                // Call the delegate.
                double results = method(10.4, 7.451);

                // Display the results.
                Console.WriteLine("\nThe result is: {0}", results);
            }
            catch (Exception e)
            {
                Console.WriteLine("\nEXCEPTION: {0}.", e.Message);
            }

            // Pause so we can look at the console window.
            Console.Write("\n\nPress <ENTER> to end: ");
            Console.ReadLine();
        }
Beispiel #36
0
        static void Main(string[] args)
        {
            try
            {
                // Display a message to show we're in Main().
                Console.WriteLine("Starting the program.");

                // Get the number of milliseconds from the arguments
                // passed in from the command line.
                int milliseconds = GetMilliseconds(args[0]);

                // Create the ComplicatedCalculator object.
                ComplicatedCalculator cc =
                    new ComplicatedCalculator(milliseconds);

                // Create the delegate object.
                DoSomething method = new DoSomething(cc.CalculateValue);

                // Create the callback delegate.
                AsyncCallback callbackMethod =
                    new AsyncCallback(ComputationComplete);

                // Create a string that will be displayed in the
                // callback method.
                string thanksString = "Main() is very happy now!";

                // Call the delegate asynchronously.
                IAsyncResult asynchStatus = method.BeginInvoke
                    (10.4, 7.451, callbackMethod, thanksString);

                // Display some messages to show that Main() is still
                // responsive while the calculation is going on.
                Console.WriteLine("\nNow I'm going to go do something else.");
                System.Threading.Thread.Sleep(1500);
                Console.WriteLine("Like talk about the weather.");
                System.Threading.Thread.Sleep(1500);
                Console.WriteLine("Or the latest news.");
                System.Threading.Thread.Sleep(1500);
                Console.WriteLine("You know, my foot hurts.");
                System.Threading.Thread.Sleep(1500);
                Console.WriteLine("I love hotdogs!");
                System.Threading.Thread.Sleep(1500);
                Console.WriteLine("How much is a shake at Burgermaster?");
                System.Threading.Thread.Sleep(1500);
                Console.WriteLine("Ok, now I'm getting hungry!");
                System.Threading.Thread.Sleep(1500);
            }
            catch (Exception e)
            {
                Console.WriteLine("\nEXCEPTION: {0}.", e.Message);
            }

            // Pause so we can look at the console window.
            Console.Write("\n\nPress <ENTER> to end: ");
            Console.ReadLine();
        }
Beispiel #37
0
        static void Main(string[] args)
        {
            try
            {
                // Display a message to show we're in Main().
                Console.WriteLine("Starting the program.");

                // Get the number of milliseconds from the arguments
                // passed in from the command line.
                int milliseconds = GetMilliseconds(args[0]);

                // Create the ComplicatedCalculator object.
                ComplicatedCalculator cc =
                    new ComplicatedCalculator(milliseconds);

                // Create the delegate object.
                DoSomething method = new DoSomething(cc.CalculateValue);

                // Call the delegate asynchronously.
                IAsyncResult asynchStatus =
                    method.BeginInvoke(10.4, 7.451, null, null);

                // Poll to see if the asynchronous call is done.
                while (!asynchStatus.IsCompleted)
                {
                    System.Threading.Thread.Sleep(750);
                    Console.WriteLine
                        ("\nSeeing if the asynch call is done.");
                }

                // Get the result of the asynchronous call.
                double results = method.EndInvoke(asynchStatus);

                // Display the results.
                Console.WriteLine("\nThe result is: {0}", results);
            }
            catch (Exception e)
            {
                Console.WriteLine("\nEXCEPTION: {0}.", e.Message);
            }

            // Pause so we can look at the console window.
            Console.Write("\n\nPress <ENTER> to end: ");
            Console.ReadLine();
        }