如果我通过2个不同的任务或线程增加一个静态,我需要锁定它吗?
我有这个类将同时由多个线程使用,它返回一个代理在线程内使用,但我不想在每个线程同时使用相同的代理,所以我想增加一个静态整数是最好的方法,有什么建议吗?
class ProxyManager
{
//static variabl gets increased every Time GetProxy() gets called
private static int Selectionindex;
//list of proxies
public static readonly string[] proxies = {};
//returns a web proxy
public static WebProxy GetProxy()
{
Selectionindex = Selectionindex < proxies.Count()?Selectionindex++:0;
return new WebProxy(proxies[Selectionindex]) { Credentials = new NetworkCredential("xxx", "xxx") };
}
}
Run Code Online (Sandbox Code Playgroud)
根据选定的答案
if(Interlocked.Read(ref Selectionindex) < proxies.Count())
{
Interlocked.Increment(ref Selectionindex);
}
else
{
Interlocked.Exchange(ref Selectionindex, 0);
}
Selectionindex = Interlocked.Read(ref Selectionindex);
Run Code Online (Sandbox Code Playgroud) 我使用ASP.NET编写了一个Web服务(在C#中),我正在尝试使用NuSOAP编写一个示例PHP客户端.我绊倒的地方是如何做到这一点的例子; 一些显示soapval正在使用(我不太了解参数-比如通过false为string类型等),而另一些则只是采用了直板array秒.假设我所报告的Web服务的WSDL http://localhost:3333/Service.asmx?wsdl看起来像:
POST /Service.asmx HTTP/1.1
Host: localhost
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://tempuri.org/webservices/DoSomething"
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<DoSomething xmlns="http://tempuri.org/webservices">
<anId>int</anId>
<action>string</action>
<parameters>
<Param>
<Value>string</Value>
<Name>string</Name>
</Param>
<Param>
<Value>string</Value>
<Name>string</Name>
</Param>
</parameters>
</DoSomething>
</soap:Body>
</soap:Envelope>
Run Code Online (Sandbox Code Playgroud)
我的第一次PHP尝试看起来像:
<?php
require_once('lib/nusoap.php');
$client = new nusoap_client('http://localhost:3333/Service.asmx?wsdl');
$params = array(
'anId' => 3, //new soapval('anId', 'int', 3),
'action' => 'OMNOMNOMNOM',
'parameters' => array(
'firstName' => 'Scott',
'lastName' => 'Smith'
)
); …Run Code Online (Sandbox Code Playgroud) 我正在创建一个非常有限的Time类,我想在其中使用核心Time类的parse方法.所以我最终得到这样的东西......
class Time
def parse(str)
@time = # I want to use Time.parse here
end
end
Run Code Online (Sandbox Code Playgroud)
如何在不重命名类的情况下突破我新定义的Time类并访问核心Time类?
我正在学习Ruby,并认为我对以下代码很聪明:
[@start,@end].map!{ |time| time += operation == :add ? amount : -(amount) }
Run Code Online (Sandbox Code Playgroud)
其中@start,@ end是两个模块级变量,操作可以是:add或:sub,而amount是一个浮点数,用于调整@start和@end.
当然,它只为我节省了一行代码,但为什么这种方法不起作用,我怎么能得到类似的东西呢?
(我的预期输出是相应地修改@ start/@ end,但是单元测试显示它们保持原始值.)