我有一个 WCF 服务,它提供了一种创建文件的方法。有时这个文件需要一点时间才能出现,如果之后立即调用其他依赖于该文件存在的方法,它们就会失败。因此,我想在继续之前检查文件是否已出现。
在我的客户端类中,我可以调用服务方法,然后循环直到文件出现,然后再继续 - 这非常有效。但是如果我循环直到文件出现在服务方法中,它永远不会发现文件已经创建 -除非我在检查之前调用 MessageBox.Show() 。如果我这样做了,它几乎会立即找到它,就像我从客户那里调用它一样。
该文件在服务方法正在寻找它的时候肯定存在(编辑:不使用 File.Exists() 正如我之前写的那样) - 那么为什么找不到它呢?为什么 MessageBox.Show() 解决了这个问题?
我假设它一定是一个我不明白的线程问题,因为它在服务外部工作,并且如果你调用 MessageBox.Show() (这会阻塞 UI 线程?),但我有点损失,所以任何帮助将不胜感激。
更多信息:如果这与线程问题相关,该服务由正在运行的 GUI 应用程序作为插件托管。感谢大家。
编辑:这是代码的一个版本。我最初没有发布这个,因为它使用了第三方库,所以我不确定它有多大帮助:
// The WCF service, in which HasCompiled(name) never
// returns true unless MessageBox.Show() is called:
public void CompileScript(string name)
{
// CompileFile outputs a file to disk:
string debug = NWN2Toolset.NWN2ToolsetMainForm.Compiler.CompileFile(script.Name,GetModuleTempPath());
if (debug.Length > 0)
throw new InvalidDataException("'" + name + "' could not be compiled: " + debug);
// If the following line is commented out, this method never returns:
MessageBox.Show("blabla");
while (!HasCompiled(name));
}
public bool HasCompiled(string name)
{
NWN2GameModule module = GetModule();
OEIResRef cResRef = new OEIResRef(name);
IResourceEntry entry = module.Repository.FindResource(cResRef,resourceType);
return entry != null;
}
// The client class, in which HasCompiled(name) returns true almost immediately:
[Test]
public void TestCompilesScript()
{
service.AddScript(name,scriptContents);
service.CompileScript(name);
while (!service.HasCompiled(name)) {
Console.WriteLine("HasCompiled(" + name+ ") == false.");
}
Console.WriteLine("HasCompiled(" + name+ ") == true.");
}